Exemplo n.º 1
0
void ScreenSurface::fillColor(Uint8 r, Uint8 g, Uint8 b) const
{
     if ( SDL_FillRect(pScreen, 0, SDL_MapRGB(pScreen->format, r, g, b)) < 0 )
         throw ErrorInfo(SDL_GetError());
}
Exemplo n.º 2
0
//-----------------------------------------------------------------------------
int SDL_main(int argc, char *argv[]) {
	// NOTE: check for the correct number of arguements
	if(argc<2) {
		fprintf(stderr, "Error: need a level name.\n");
		return -1;
	}

	// NOTE: add the sqlite db to the levels directory
	char filename[0xFF];
	sprintf(filename, "levels/%s.db", argv[1]);

	// NOTE: open database connection
	if(sqlite3_open_v2(filename, &db, SQLITE_OPEN_READONLY, NULL)) {
		fprintf(stderr, "sqlite3_open: %s\n", sqlite3_errmsg(db));
		sqlite3_close(db);
		return -1;
	}

	/* === */

	start();

	/* === */

	int wallSprite00Inds[2*3] = {
		03, 04,
		35, 36,
		67, 68
	};

	SDL_Color wall00Color = {0xFF,0xFF,0xFF,0xFF};
	SDL_Surface *wallSprite00 = buildSprite(2, 3, wall00Color, wallSprite00Inds);

	int floorSprite00Inds[2*3] = {
		17, 18,
		49, 50,
		81, 82
	};

	SDL_Color floorSprite00Color = {0x33,0x33,0x33,0xFF};
	SDL_Surface *floorSprite00 = buildSprite(2, 3, floorSprite00Color, floorSprite00Inds);

	int doorSprite00Inds[2*3] = {
		29, 30,
		61, 62,
		93, 94
	};

	SDL_Color doorSprite00Color = {0xFF,0xFF,0xFF,0xFF};
	SDL_Surface *doorSprite00 = buildSprite(2, 3, doorSprite00Color, doorSprite00Inds);

	int wallSprite01Inds[2*3] = {
		 97,  98,
		129, 130,
		161, 162
	};

	SDL_Color wall01Color = {0xFF,0xFF,0xFF,0xFF};
	SDL_Surface *wallSprite01 = buildSprite(2, 3, wall01Color, wallSprite01Inds);

	int wallSprite02Inds[2*3] = {
		105, 106,
		137, 138,
		169, 170
	};

	SDL_Color wallSprite02Color = {0xFF,0xFF,0xFF,0xFF};
	SDL_Surface *wallSprite02 = buildSprite(2, 3, wallSprite02Color, wallSprite02Inds);

	/* === */

	while(running) {
		/* === */

		pollInput();

		SDL_RenderClear(renderer);
		SDL_FillRect(screen, 0, 0x00);

		/* === */

		loadTiles();

		SDL_Rect tempRect = {
			0, 0, SPRITE_W*2, SPRITE_H*3
		};

		int i, j;
		for(j=0; j<12; j++) {
			for(i=0; i<30; i++) {
				tempRect.x = SPRITE_W*2*i;
				tempRect.y = SPRITE_H*3*j;

				switch(lvl.tiles[j][i]) {
					case 0x01: {
						SDL_BlitSurface(wallSprite00, NULL, screen, &tempRect);
					} break;
					case 0x02: {
						SDL_BlitSurface(doorSprite00, NULL, screen, &tempRect);
					} break;
					case 0x03: {
						SDL_BlitSurface(wallSprite01, NULL, screen, &tempRect);
					} break;
					case 0x04: {
						SDL_BlitSurface(wallSprite02, NULL, screen, &tempRect);
					} break;
					default: {
						SDL_BlitSurface(floorSprite00, NULL, screen, &tempRect);
					} break;
				}
			}
		}

		/* === */

		int pitch;
		void *pixels;

		// NOTE: get the pixels for the screen texture
		SDL_LockTexture(texture, NULL, &pixels, &pitch);

		// NOTE: set the pixels for the screen texture
		SDL_ConvertPixels(
			screen->w,
			screen->h,
			screen->format->format,
			screen->pixels,
			screen->pitch,
			SDL_PIXELFORMAT_RGBA8888,
			pixels, pitch
		);

		// NOTE: lock the texture so that it may be presented
		SDL_UnlockTexture(texture);

		// NOTE: present the texture
		SDL_RenderCopy(renderer, texture, NULL, NULL);
		SDL_RenderPresent(renderer);

		SDL_Delay(10);

		/* === */
	}

	/* === */

	SDL_FreeSurface(wallSprite00);
	wallSprite00 = NULL;

	SDL_FreeSurface(floorSprite00);
	floorSprite00 = NULL;

	SDL_FreeSurface(doorSprite00);
	doorSprite00 = NULL;

	SDL_FreeSurface(wallSprite01);
	wallSprite01 = NULL;

	SDL_FreeSurface(wallSprite02);
	wallSprite02 = NULL;

	/* === */

	quit();

	/* === */

	// NTOE: close the database connection
	sqlite3_close(db);
	db = NULL;

	fclose(stderr);
	return 0;
}
Exemplo n.º 3
0
/**
**  Initialize the fog of war.
**  Build tables, setup functions.
*/
void CMap::InitFogOfWar()
{
	//calculate this once from the settings and store it
	FogOfWarColorSDL = Video.MapRGB(TheScreen->format, FogOfWarColor);

	Uint8 r, g, b;
	SDL_Surface *s;

	FogGraphic->Load();

#if defined(USE_OPENGL) || defined(USE_GLES)
	if (!UseOpenGL)
#endif
	{
		//
		// Generate Only Fog surface.
		//
		s = SDL_CreateRGBSurface(SDL_SWSURFACE, PixelTileSize.x, PixelTileSize.y,
								 32, RMASK, GMASK, BMASK, AMASK);

		SDL_GetRGB(FogOfWarColorSDL, TheScreen->format, &r, &g, &b);
		Uint32 color = Video.MapRGB(s->format, r, g, b);

		SDL_FillRect(s, NULL, color);
		OnlyFogSurface = SDL_DisplayFormat(s);
		SDL_SetAlpha(OnlyFogSurface, SDL_SRCALPHA | SDL_RLEACCEL, FogOfWarOpacity);
		VideoPaletteListRemove(s);
		SDL_FreeSurface(s);

		//
		// Generate Alpha Fog surface.
		//
		if (FogGraphic->Surface->format->BytesPerPixel == 1) {
			s = SDL_DisplayFormat(FogGraphic->Surface);
			SDL_SetAlpha(s, SDL_SRCALPHA | SDL_RLEACCEL, FogOfWarOpacity);
		} else {
			// Copy the top row to a new surface
			SDL_PixelFormat *f = FogGraphic->Surface->format;
			s = SDL_CreateRGBSurface(SDL_SWSURFACE, FogGraphic->Surface->w, PixelTileSize.y,
									 f->BitsPerPixel, f->Rmask, f->Gmask, f->Bmask, f->Amask);
			SDL_LockSurface(s);
			SDL_LockSurface(FogGraphic->Surface);
			for (int i = 0; i < s->h; ++i) {
				memcpy(reinterpret_cast<Uint8 *>(s->pixels) + i * s->pitch,
					   reinterpret_cast<Uint8 *>(FogGraphic->Surface->pixels) + i * FogGraphic->Surface->pitch,
					   FogGraphic->Surface->w * f->BytesPerPixel);
			}
			SDL_UnlockSurface(s);
			SDL_UnlockSurface(FogGraphic->Surface);

			// Convert any non-transparent pixels to use FogOfWarOpacity as alpha
			SDL_LockSurface(s);
			for (int j = 0; j < s->h; ++j) {
				for (int i = 0; i < s->w; ++i) {
					Uint32 c = *reinterpret_cast<Uint32 *>(&reinterpret_cast<Uint8 *>(s->pixels)[i * 4 + j * s->pitch]);
					Uint8 a;

					Video.GetRGBA(c, s->format, &r, &g, &b, &a);
					if (a) {
						c = Video.MapRGBA(s->format, r, g, b, FogOfWarOpacity);
						*reinterpret_cast<Uint32 *>(&reinterpret_cast<Uint8 *>(s->pixels)[i * 4 + j * s->pitch]) = c;
					}
				}
			}
			SDL_UnlockSurface(s);
		}
		AlphaFogG = CGraphic::New("");
		AlphaFogG->Surface = s;
		AlphaFogG->Width = PixelTileSize.x;
		AlphaFogG->Height = PixelTileSize.y;
		AlphaFogG->GraphicWidth = s->w;
		AlphaFogG->GraphicHeight = s->h;
		AlphaFogG->NumFrames = 16;//1;
		AlphaFogG->GenFramesMap();
		AlphaFogG->UseDisplayFormat();
	}

	VisibleTable.clear();
	VisibleTable.resize(Info.MapWidth * Info.MapHeight);
}
Exemplo n.º 4
0
int main(int argc, char *argv[])
{
    
    //Network vars
    int udpSd, tcpSd;
    char buffer[5];
    int myId;
    
    //SDL vars
    SDL_Event event;
    
    //Screen
    SDL_Surface* screen = NULL;
    
    //Tanks
    SDL_Surface* blueTank = NULL;
    SDL_Surface* blueCannon = NULL;
    SDL_Surface* redTank = NULL;
    SDL_Surface* redCannon = NULL;
    
    //Bullet
    SDL_Surface* bullet = NULL;
    
    //WorldMap
    SDL_Surface* worldMap = NULL;
    
    //rotation Images
    //SDL_Surface* rotatedTank[6] = {NULL,NULL,NULL,NULL,NULL,NULL};
    //SDL_Surface* rotatedCannon[6] = {NULL,NULL,NULL,NULL,NULL,NULL};
    SDL_Surface* rotatedBullet[6] = {NULL,NULL,NULL,NULL,NULL,NULL};
    
    //SDL_Rect Tankoffset[6] = {400,300,0,0};
    //SDL_Rect Cannonoffset[6] = {400,300,0,0};

    //UserInterface vars
    SDL_Surface* UIhealth;
    SDL_Surface* UIreload;
    SDL_Surface* UIredPoints;
    SDL_Surface* UIbluePoints;
    
    TTF_Font *font = NULL;
    TTF_Font *reloadFont = NULL;
    
    SDL_Color textColor = { 255, 255, 255 };
    char textBuffer[32];
    char reload[32] = "FIRE: ";
    
    
    //Thread vars
    pthread_t reciveUdpData;

    //Game vars
    int run;
    struct playerInfo player[6];
    struct timerInfo fps;
    struct cameraInfo camera;
    int bulletAngle[6];
    
    //int oldCannonAngle[6];
    //int oldTankAngle[6];
    
    //Other vars
    int i;
    
    //Inits the player struct
    for (i = 0; i < MAX_PLAYERS; i++)
    {
        player[i].slot = -1;
        player[i].connected = 0;
    }
    
    //inits Sdl and opens the screen
    screen = init_sdl();
    if(screen == 0)
    {
        printf("Error initializing SDL\n");
        return 0;
    }
    
    //Makes the connection to the server
    if(!(init_udp_tcp(&udpSd, &tcpSd, argv[1], argv[2])))
    {
        printf("Error making connection\n");
        return 0;
    }
    
    //load the images (Function maybe)
    blueTank = load_image( "./images/blueTank.bmp" );
    blueCannon = load_image( "./images/blueCannon.bmp" );
    redTank = load_image( "./images/redTank.bmp" );
    redCannon = load_image( "./images/redCannon.bmp" );
    worldMap = load_image( "./images/worldMap.bmp" );
    bullet = load_image( "./images/bullet.bmp" );

    //Load the fonts
    font = TTF_OpenFont( "./fonts/Army.ttf", 24 );
    reloadFont = TTF_OpenFont( "./fonts/Armyfat.ttf", 24 );
    
    //Moves udp info to global var
    udpInfo.udpSd = udpSd;
    strcpy(udpInfo.serverIp, argv[1]);

    //Recives the first information from the server
    recv(tcpSd, buffer, sizeof(buffer), 0);
    myId = atoi(buffer);
    
    //Starts the Recive data thread
    pthread_create( &reciveUdpData, NULL, recive_udp_data, &(player));

    while (run)
    {
        //Start the timer
        timer_start(&fps);

        while( SDL_PollEvent( &event ) )
        {
            
            if( event.type == SDL_QUIT || event.key.keysym.sym == SDLK_ESCAPE)
            {
                run = FALSE;
            }
            
            handel_input(&event, tcpSd );
            
        }
        
        camera.xCord = -player[myId].xCord;
        camera.yCord = -player[myId].yCord;
        
        
        //From here we draw stuff on the screen
        SDL_FillRect(screen,NULL, 0x000000);

        
        //Draws WorldMAps
        draw_map(player[myId].xCord,player[myId].yCord, worldMap, screen);

        
        //DISPLAYES YOUR TANK+++++++++++++++++++++++++++++
        if (player[myId].team == 1)
        {
            draw_tank_self(player[myId].tankAngle, blueTank, screen);
            draw_cannon_self(player[myId].cannonAngle, blueCannon, screen);
        }
        else
        {
            draw_tank_self(player[myId].tankAngle, redTank, screen);
            draw_cannon_self(player[myId].cannonAngle, redCannon, screen);
        }
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

        //DISPLAYES OTHER TANKS+++++++++++++++++++++++++++++
        for (i = 0; i < MAX_PLAYERS; i++)
        {
            if (player[i].slot == myId)
            {
                continue;
            }
            
            if (player[i].slot > -1 && player[i].connected == 1)
            {
                if (player[i].team == 1)
                {
                    draw_tank_other(player[i].xCord,player[i].yCord,camera.xCord,camera.yCord,player[i].tankAngle,blueTank,screen);
                    if (player[i].dead == 0)
                        draw_cannon_other(player[i].xCord,player[i].yCord,camera.xCord,camera.yCord,player[i].cannonAngle,blueCannon,screen);
                }
                else
                {
                    draw_tank_other(player[i].xCord,player[i].yCord,camera.xCord,camera.yCord,player[i].tankAngle,redTank,screen);
                    if (player[i].dead == 0)
                        draw_cannon_other(player[i].xCord,player[i].yCord,camera.xCord,camera.yCord,player[i].cannonAngle,redCannon,screen);
                }
            }
        }
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        
        //DRAWS ALL THE BULLETS ON THE SCREEEN+++++++++++++++++++++++++++
        for (i = 0; i < MAX_PLAYERS; i++)
        {
            if (player[i].slot > -1 && player[i].connected == 1)
            {
                if (player[i].fire > 0)
                {
                    if (bulletAngle[i] == 0)
                    {
                        SDL_FreeSurface( rotatedBullet[i] );
                        rotatedBullet[i] = rotozoomSurface(bullet,player[i].cannonAngle,1.0,0);
                        playSound(soundShoot);
                    }
                    draw_bullet(&player[i], &camera, rotatedBullet[i], screen );
                    bulletAngle[i] = 1;
                }
                
                if (player[i].fire == 0)
                {
                    bulletAngle[i]=0;
                }
            }
        }
        //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        
        //DRAWS THE USER INTERFACE ON SCREEN+++++++++++++++++++++++++++++
        
        textColor.r=0;
        textColor.g=0;
        textColor.b=255;
        sprintf(textBuffer, "BLUE POINTS: %d", bluePoints);
        UIbluePoints = TTF_RenderText_Solid( font, textBuffer, textColor );
        draw_UI( 10, 10, UIbluePoints, screen);
        
        textColor.r=255;
        textColor.g=0;
        textColor.b=0;
        sprintf(textBuffer, "RED POINTS: %d", redPoints);
        UIredPoints = TTF_RenderText_Solid( font, textBuffer, textColor );
        draw_UI( 600, 10, UIredPoints, screen);
        
        textColor.r=255;
        textColor.g=0;
        textColor.b=0;
        sprintf(textBuffer, "HP: %d", player[myId].healthPoints);
        UIhealth = TTF_RenderText_Solid( font, textBuffer, textColor );
        draw_UI( 20, 570, UIhealth, screen);
        
        
        textColor.r=255;
        textColor.g=0;
        textColor.b=0;
        if (player[myId].fire == 0)
        {
            strcpy(reload, "FIRE: READY");
            UIreload = TTF_RenderText_Solid( font, reload, textColor );
        }
        else
        {
            strcpy(reload, "FIRE: RELOADING");
            UIreload = TTF_RenderText_Solid( font, reload, textColor );
        
        }
        draw_UI( 580, 570, UIreload, screen);


        //Update Screen
        SDL_Flip( screen );
        

        //Cap the frame rate
        if( timer_get_ticks(&fps) < 1000 / FPS )
        {
            SDL_Delay( ( 1000 / FPS ) - timer_get_ticks(&fps) );
        }

    }
    
    
    pthread_cancel(reciveUdpData);
    return 0;
}
Exemplo n.º 5
0
// plays the intro sequence
void playIntro()
{
	SDL_Surface *text;
	int intro = 0;
	int iAlpha = 0;
	int iPhase = 0;
	Sprite *spr;
	gBool fade = true;
	TTF_Font *font;
	SDL_Rect dest;
	int fadeSpeed = 1;
	Uint8 *keys;

	spr = LoadSprite("images/kimmy.png",506,565);
	font = TTF_OpenFont("fonts/font1.ttf",60);

	while(++intro<1000)
	{
		SDL_PumpEvents();
		keys = SDL_GetKeyState(NULL);
		if(keys[SDLK_ESCAPE])
			intro = 1000;
		
		ResetBuffer();
		if(spr != NULL)
		{
			fprintf(stderr,"intro: %i iAlpha: %i iPhase: %i\n",intro,iAlpha,iPhase);
			SDL_FillRect(screen,&screen->clip_rect,SDL_MapRGB(screen->format, 0,0,0));

			switch(iPhase)
			{
			case 0:
				fadeSpeed = 1;
				text = TTF_RenderText_Solid(font,"Vincent Scuorzo Presents",color);
				dest.x = (screen->w-text->w)*.5;
				dest.y = (screen->h-text->h)*.5;
				SDL_SetAlpha( text, SDL_SRCALPHA|SDL_RLEACCEL, iAlpha );
				SDL_BlitSurface(text,NULL,screen,&dest);
				break;
			case 1:
				fadeSpeed = 1;
				SDL_SetAlpha( spr->image, SDL_SRCALPHA|SDL_RLEACCEL, iAlpha );
				DrawSprite(spr,screen,(screen->w-spr->w)*.5,(screen->h-spr->h)*.5,0);
				break;
			default:
				intro = 1000;
			}

			if(iAlpha < (SDL_ALPHA_OPAQUE-fadeSpeed) && fade == true)
				iAlpha+=fadeSpeed;
			else if(iAlpha > SDL_ALPHA_TRANSPARENT && fade == false)
				iAlpha-=fadeSpeed;
			else if(iAlpha >= (SDL_ALPHA_OPAQUE-fadeSpeed) )
			{
				fade = false;
			}
			else if(iAlpha <= SDL_ALPHA_TRANSPARENT)
			{
				fade = true;
				++iPhase;
			}
		}
		else
			intro = 1000;
		NextFrame();
	}
}
Exemplo n.º 6
0
int
main ( int argc, char *argv[] )
{
    bool quit = false;
    int sprite_x = 0;
    int inc_val  = 0;
    char m[80];
    int u = 0;
    int bgX = 0;
    int bgY = 0;

    if( init() == false )
        return EXIT_FAILURE;
    if( load_files() == false )
        return EXIT_FAILURE;

    clip[0].x = 0;
    clip[0].y = 0;
    clip[0].w = 32;
    clip[0].h = 32;

    //apply_surface( 0, 0, background, screen );
    apply_surface( 10, 10, sprite_image, screen, &clip[0] );
    //apply_surface( 10, 10, sprite_image, screen );
    if( SDL_Flip( screen ) == -1 )
    {
        return EXIT_FAILURE;
    }

    next_time = SDL_GetTicks() + TICK_INTERVAL;

    while( quit == false ){

        SDL_Rect tmp;
        SDL_Rect tmp2;
        
        tmp.x = sprite_x;
        tmp.y = 0;
        tmp.w = 32;
        tmp.h = 32;

        quit = handle_events( &inc_val );

        tmp2.x = 210 + 150;
        tmp2.y = 0;
        tmp2.w = 16;
        tmp2.h = 16;

        if( rightdown )
            inc_val++;

        if( inc_val > 0 && leftdown )
            inc_val--;

        //rightdown = false;
        //leftdown = false;

        //
        //fprintf(stderr, "x = %d\n", sprite_x);

        sprintf( m, "%d", inc_val );

        message = TTF_RenderText_Solid( font, m, textColor );

        SDL_FillRect( screen, NULL, SDL_MapRGB( screen->format, 0, 0, 0 ) );
        //apply_surface( 10, 10, sprite_image, screen, &tmp );
        //apply_surface( 100, 100, sprite_image2, screen, &tmp2 );
        draw();

        bgX -= 2;

        if( bgX <= -background->w ){
            bgX = 0;
        }
        /*
        if( !updown && u != 50 ){
            u = 100;

        }
        */
        apply_surface( bgX, bgY, background, screen );
        apply_surface( bgX + background->w, bgY, background, screen );
        apply_surface( 50, 50, message, screen );
        //apply_surface( 10, 10, sprite_image, screen );
        if( SDL_Flip( screen ) == -1 )
        {
            return EXIT_FAILURE;
        }

        sprite_x = (sprite_x + 32) % 256;
        //SDL_Delay(30);
        SDL_Delay( time_left() );
        //SDL_free( tmp );
        next_time += TICK_INTERVAL;
    }

    //SDL_Delay(5000);

    return EXIT_SUCCESS;
}/* ----------  end of function main  ---------- */
Exemplo n.º 7
0
int
main (int argc, char **argv)
{
    SDL_Surface *image;
    nile_t *nl;
    char mem[500000];
    uint32_t texture_pixels[TEXTURE_WIDTH * TEXTURE_HEIGHT] = {0};
    real angle = 0;
    real scale;

    if (SDL_Init (SDL_INIT_VIDEO) == -1)
        DIE ("SDL_Init failed: %s", SDL_GetError ());
    if (!SDL_SetVideoMode (DEFAULT_WIDTH, DEFAULT_HEIGHT, 0,
                           SDL_HWSURFACE | SDL_ANYFORMAT | SDL_DOUBLEBUF))
        DIE ("SDL_SetVideoMode failed: %s", SDL_GetError ());
    image = SDL_GetVideoSurface ();

    nl = nile_new (NTHREADS, mem, sizeof (mem));

    ilInit ();
    ilBindImage (iluGenImage ());
    if (argc < 3)
        return -1;
    printf ("loading: %s\n", argv[1]);
    ilLoadImage (argv[1]);
    ilCopyPixels (0, 0, 0, TEXTURE_WIDTH, TEXTURE_HEIGHT, 1, IL_BGRA,
                  IL_UNSIGNED_BYTE, &texture_pixels);
    int filter = atoi (argv[2]);

    for (;;) {
        angle += 0.001;
        scale = fabs (angle - (int) angle - 0.5) * 10;
        SDL_Event event;
        if (SDL_PollEvent (&event) && event.type == SDL_QUIT)
            break;

        SDL_FillRect (image, NULL, 0);
        SDL_LockSurface (image);

            matrix_t M = matrix_new ();
            M = matrix_translate (M, 250, 250);
            M = matrix_rotate (M, angle);
            M = matrix_scale (M, scale, scale);
            M = matrix_translate (M, -250, -250);
            matrix_t I = matrix_inverse (M);

            nile_Kernel_t *texture =
                gezira_ReadFromImage_ARGB32 (nl, texture_pixels, TEXTURE_WIDTH,
                                             TEXTURE_HEIGHT, TEXTURE_WIDTH);
            /*
             */
            texture = nile_Pipeline (nl,
                    gezira_ImageExtendReflect (nl, TEXTURE_WIDTH, TEXTURE_HEIGHT),
                    texture, NULL);
            if (filter == 2)
                texture = gezira_BilinearFilter (nl, texture);
            if (filter == 3)
                texture = gezira_BicubicFilter (nl, texture);
            /*
             */
            texture = nile_Pipeline (nl, 
                gezira_TransformPoints (nl, I.a, I.b, I.c, I.d, I.e - 150, I.f - 125),
                texture, NULL);
            nile_Kernel_t *pipeline = nile_Pipeline (nl,
                gezira_TransformBeziers (nl, M.a, M.b, M.c, M.d, M.e, M.f),
                gezira_ClipBeziers (nl, 0, 0, DEFAULT_WIDTH, DEFAULT_HEIGHT),
                gezira_Rasterize (nl),
                gezira_ApplyTexture (nl, texture),
                gezira_WriteToImage_ARGB32 (nl, image->pixels,
                                            DEFAULT_WIDTH, DEFAULT_HEIGHT,
                                            image->pitch / 4),
                NULL);

            nile_feed (nl, pipeline, path, 6, path_n, 1);
            nile_sync (nl);

        SDL_UnlockSurface (image);
        SDL_Flip (image);
    }

    nile_free (nl);
    printf ("done\n");

    return 0;
}
Exemplo n.º 8
0
int graphics( float heading)
{

        SDL_Rect outerRingposition;
        SDL_Rect compassNeedlePosition;


        SDL_Rect topLine1;
        topLine1.x = 20;
        topLine1.y = 100;
        topLine1.w = 0;
        topLine1.h = 0;


        SDL_Color colorWhite = {255,255,255,0};


        char headingString[8] = "";

	//Clear previous image
        SDL_FillRect(screen, NULL, 0x000000);

	//Convert heading value which is a float to a string
        snprintf(headingString, 7, "%7.3f", heading);

        textSurface = TTF_RenderText_Solid(font, headingString, colorWhite);

	//Rotate the heading
        currentDegressRotated =  rotozoomSurface(textSurface, TEXTANGLE, 1.0, 0);

	//Position the outer ring in the center of display
        outerRingposition.x = (SCREEN_WIDTH - compatibleOuterRing->w)/2;
        outerRingposition.y = (SCREEN_HEIGHT - compatibleOuterRing->h)/2;

	//Position compass needle
        compassNeedlePosition.x = (SCREEN_WIDTH - compatibleCompassNeedle->w)/2;
        compassNeedlePosition.y = 20;

	//Rotate needle based on angle. Add 90 degrees for correction.
        rotation = rotozoomSurface(compatibleCompassNeedle, heading+90, 1.0, 0);
        if (rotation == NULL) printf("error rotating needle\n");

        //recenter pivote for rotation
        compassNeedlePosition.x -= rotation->w/2-compatibleCompassNeedle->w/2;
        compassNeedlePosition.y -= rotation->h/2-compatibleCompassNeedle->h/2;

        // put the image on the screen surface
        SDL_BlitSurface(currentDegressRotated, NULL, screen, &topLine1);
        SDL_BlitSurface(compatibleOuterRing, NULL, screen, &outerRingposition);
        SDL_BlitSurface(rotation, NULL, screen, &compassNeedlePosition);

	// send the screen surface to be displayed
        SDL_Flip(screen);

        SDL_FreeSurface(currentDegressRotated);
        SDL_FreeSurface(textSurface);
        SDL_FreeSurface(screen);
        SDL_FreeSurface(rotation);

        return 0;
}
Exemplo n.º 9
0
void Screen::preRender() {
  SDL_FillRect(screen,NULL,0x00FF00);
}
Exemplo n.º 10
0
/*Ceci est un menu special
 * Il ne suit pas les memes
 * regles que les autres menus
 * Accessoirement c'est tres moche*/
void options_menu(config *cfg)
{
	config tmp = *cfg;
	int i, j=0, nb=9, couleur[nb], available[nb], selection=0;
	SDL_Surface *pac[2], *ghost[2], *fleche[2];
	SDL_Rect pos;
	POINT p1;
	Input in;
	char title[64];
	char options[nb][64];

	for(i=0; i<nb; i++)
	{
		available[i]=1;
		couleur[i]=blanc;
	}
	pac[0]   = IMG_Load("image/pacman/2.png");
	pac[1]   = IMG_Load("image/pacman/3.png");
	ghost[0] = IMG_Load("image/ghosts/2.png");
	ghost[1] = IMG_Load("image/ghosts/3.png");
	fleche[0] = IMG_Load("image/menu/triangler.png");
	fleche[1] = IMG_Load("image/menu/trianglel.png");
	if(pac == NULL || ghost == NULL)
	{
		fprintf(stderr, "Erreur loading pngs in >>options_menu()<<\n");
		exit(EXIT_FAILURE);
	}
	memset(&in,0,sizeof(in));
	strcpy(title, "OPTIONS");
	strcpy(options[0], "Nb players");
	sprintf(options[1], "%d", cfg->nb_players);
	strcpy(options[2], "Player 1");
	strcpy(options[3], "Player 2");
	strcpy(options[4], "Sound");
	strcpy(options[5], "Reset score");
	strcpy(options[6], "Reset");
	strcpy(options[7], "Cancel");
	strcpy(options[8], "Save");
	available[1]=0;
	available[4]=0;
	if(cfg->nb_players==0)
	{
		available[2]=0;
		available[3]=0;
	}
	else if(cfg->nb_players==1) available[3]=0;
	DELAY=60;
	while(!in.quit)
	{
		SDL_Delay(DELAY);
		for(i=0; i<nb; i++)
		{
			if(!available[i] && i!=1) couleur[i]=gris;
			else couleur[i]=blanc;
		}
		couleur[selection]=blanc;
		UpdateEvents(&in);
		if(in.key[SDLK_ESCAPE]) exit(EXIT_SUCCESS);
		else if(in.key[SDLK_RETURN])
		{
			in.key[SDLK_RETURN]=0;
			if(selection==nb-4) //reset score
			{
				reset_score("data/results.txt");
				reset_score("data/survivor.txt");
			}
			if(selection==nb-3)
			{
				load_default_config(cfg); //default config
				sprintf(options[1], "%d", cfg->nb_players);
				available[2]=1;
				available[3]=0;
			}
			else if(selection==nb-2) //Cancel
			{
				*cfg=tmp;
				return;
			}
			else if(selection==nb-1) //Save
			{
				if(cfg->nb_players==2)
				{
					if(cfg->players[0].character == PACMAN && cfg->players[1].character == PACMAN)
						fprintf(stderr, "Only one pacman is allowed!\n"); //Should not happen
					else return;
				}
				else return;
			}
		}
		else if(in.key[SDLK_DOWN])
		{
			in.key[SDLK_DOWN]=0;
			selection=(selection+1)%nb;
			while(!available[selection]) selection=(selection+1)%nb;
		}
		else if(in.key[SDLK_UP])
		{
			in.key[SDLK_UP]=0;
			if(!(selection)) selection=nb-1;
			else selection=(selection-1)%nb;
			while(!available[selection])
			{
				if(!selection) selection=nb-1;
				else selection=(selection-1)%nb;
			}
		}
		else if(in.key[SDLK_LEFT])
		{
			in.key[SDLK_LEFT]=0;
			if(selection==0) {
				if(cfg->nb_players>0)
				{
					available[cfg->nb_players+1]=0;
					cfg->nb_players=cfg->nb_players-1;
					sprintf(options[1], "%d", cfg->nb_players);
				}
			}
			else if(selection==2 || selection==3) {
				if(cfg->players[selection-2].character == PACMAN) cfg->players[selection-2].character = GHOST;
				else if(cfg->players[selection-2].character == GHOST) cfg->players[selection-2].character = PACMAN;
			}
		}
		else if(in.key[SDLK_RIGHT])
		{
			in.key[SDLK_RIGHT]=0;
			if(selection==0)
			{
				if(cfg->nb_players<2) {
					available[cfg->nb_players+2]=1;
					cfg->nb_players=(cfg->nb_players+1);
					sprintf(options[1], "%d", cfg->nb_players);
				}
			}
			else if(selection==2 || selection==3) {
				if(cfg->players[selection-2].character == PACMAN) cfg->players[selection-2].character = GHOST;
				else if(cfg->players[selection-2].character == GHOST) cfg->players[selection-2].character = PACMAN;
			}
		}
		SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0));
		couleur[selection]=jaune;

		p1.x=300; p1.y=50;
		aff_pol(title, 50, p1, jaune); //Le titre

		p1.x=310; p1.y=150;
		aff_pol(options[0], 30, p1, couleur[0]); //Nb players
		pos.x=p1.x+120; pos.y=p1.y;
		SDL_BlitSurface(fleche[1], NULL, screen, &pos);
		p1.x+=150;
		aff_pol(options[1], 30, p1, couleur[1]); //Nb players
		pos.x+=50;
		SDL_BlitSurface(fleche[0], NULL, screen, &pos);
		//Afficher des fleches

		j=(j+1)%2;
		p1.x=250; p1.y=225;
		pos.x=p1.x+10; pos.y=p1.y+50;
		aff_pol(options[2], 30, p1, couleur[2]); //Player 1
		SDL_BlitSurface(fleche[1], NULL, screen, &pos);
		pos.x+=25;
		if(cfg->players[0].character == GHOST) SDL_BlitSurface(ghost[j], NULL, screen, &pos);
		else SDL_BlitSurface(pac[j], NULL, screen, &pos);
		pos.x+=25;
		SDL_BlitSurface(fleche[0], NULL, screen, &pos);
		//Afficher des fleches

		p1.x+=200;
		pos.x=p1.x+10;
		aff_pol(options[3], 30, p1, couleur[3]); //Player 2
		SDL_BlitSurface(fleche[1], NULL, screen, &pos);
		pos.x+=25;
		if(cfg->players[1].character == GHOST) SDL_BlitSurface(ghost[j], NULL, screen, &pos);
		else SDL_BlitSurface(pac[j], NULL, screen, &pos);
		pos.x+=25;
		SDL_BlitSurface(fleche[0], NULL, screen, &pos);
		//Afficher des fleches

		p1.x=250; p1.y+=100;
		aff_pol(options[4], 30, p1, couleur[4]); //Sound
		//Afficher des images pour le son

		p1.x=250; p1.y+=75;
		aff_pol(options[5], 30, p1, couleur[5]); //Reset score

		p1.x=150; p1.y+=100;
		for(i=6; i<nb; i++)
		{
			aff_pol(options[i], 30, p1, couleur[i]);
			p1.x+=225;
		}
		SDL_Flip(screen);
	}
}
Exemplo n.º 11
0
int jeu(SDL_Surface* ecran,int choix,int difficulte,int ArduinoClavier)
{





SDL_Event event; //pour pouvoir gerer les events
SDL_ShowCursor(SDL_DISABLE);//On n'affiche plus le curseur
SDL_Surface *imageDeFond = NULL, *Note = NULL, *Note_do = NULL, *Note_re = NULL, *Note_mi = NULL, *Note_fa = NULL, *Note_sol = NULL, *Note_la = NULL, *Note_si = NULL; //Initialisation des images : on crée un pointeur pour chaque image auquel on met la valeur NULL
SDL_Rect positionFond,positionNote[TAILLE_MAX], positionNote_do,positionNote_re,positionNote_mi,positionNote_fa,positionNote_sol,positionNote_la,positionNote_si; //Initialisation des positions des images

//Initialisation positions x et y
int i; for(i=0;i<TAILLE_MAX;i++)
        {positionNote[i].x=0; positionNote[i].y=0;} //Initialisation de TOUTES les notes du morceau

positionNote_do.y = positionNote_re.y = positionNote_mi.y = positionNote_fa.y = positionNote_sol.y = positionNote_la.y = positionNote_si.y = 658;
positionNote_do.x = 265;
positionNote_re.x = 408;
positionNote_mi.x = 548;
positionNote_fa.x = 690;
positionNote_sol.x = 834;
positionNote_la.x = 973;
positionNote_si.x = 1117;
positionFond.x = 0;
positionFond.y = 0;


imageDeFond = SDL_LoadBMP("images/fond.bmp");//on indique ou est l'image de fond


//Images
Note = SDL_LoadBMP("images/notes/note.bmp") ;
Note_do = SDL_LoadBMP("images/notes/do.bmp");
Note_re = SDL_LoadBMP("images/notes/re.bmp");
Note_mi = SDL_LoadBMP("images/notes/mi.bmp");
Note_fa = SDL_LoadBMP("images/notes/fa.bmp");
Note_sol = SDL_LoadBMP("images/notes/sol.bmp");
Note_la = SDL_LoadBMP("images/notes/la.bmp");
Note_si = SDL_LoadBMP("images/notes/si.bmp");
SDL_SetColorKey(Note, SDL_SRCCOLORKEY, SDL_MapRGB(Note->format, 0,0, 255));//transparence
//

 FILE* fichier = NULL;//pour lire la "partition"




/***********Musique***************
*********************************/

FMOD_SYSTEM *system;
FMOD_SOUND *musique;//musique :/
FMOD_RESULT resultat;
FMOD_System_Create(&system);
FMOD_System_Init(system, 1, FMOD_INIT_NORMAL, NULL);

/* On ouvre la musique en fonction du choix et on ouvre la partition qui correspond (c'est gros pour pas grand chose)*/
switch(choix)
{
    case 0 :
    resultat = FMOD_System_CreateSound(system, "musiques/FrereJacques.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/FrereJacques.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 1 :
    resultat = FMOD_System_CreateSound(system, "musiques/Muse.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Muse.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 2 :
    resultat = FMOD_System_CreateSound(system, "musiques/AuClairDeLaLune.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/AuClairDeLaLune.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 3 :
    resultat = FMOD_System_CreateSound(system, "musiques/Titanic.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Titanic.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 4 :
    resultat = FMOD_System_CreateSound(system, "musiques/MJ.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/MJ.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 5 :
    resultat = FMOD_System_CreateSound(system, "musiques/Clocks.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Clocks.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 6 :
    resultat = FMOD_System_CreateSound(system, "musiques/Laputa.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Laputa.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 7 :
    resultat = FMOD_System_CreateSound(system, "musiques/YMCA.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/YMCA.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 8 :
    resultat = FMOD_System_CreateSound(system, "musiques/Changes.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Changes.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 10 :
    resultat = FMOD_System_CreateSound(system, "musiques/Dancing_in_the_Dark.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Dancing_in_the_Dark.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 11 :
    resultat = FMOD_System_CreateSound(system, "musiques/Born_to_Run.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Born_to_Run.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 12 :
    resultat = FMOD_System_CreateSound(system, "musiques/Bruno Mars.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Bruno Mars.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 13 :
    resultat = FMOD_System_CreateSound(system, "musiques/Bad day.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Bad day.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 15 :
    resultat = FMOD_System_CreateSound(system, "musiques/The Fray.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/The Fray.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 16 :
    resultat = FMOD_System_CreateSound(system, "musiques/Led Zep.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Led Zep.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 17 :
    resultat = FMOD_System_CreateSound(system, "musiques/Naruto.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Naruto.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 18 :
    resultat = FMOD_System_CreateSound(system, "musiques/Somebody to love - Queen.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Somebody to love - Queen.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    case 19 :
    resultat = FMOD_System_CreateSound(system, "musiques/Viva.mid", FMOD_SOFTWARE | FMOD_2D | FMOD_CREATESTREAM, 0, &musique);
    fichier = fopen("musiques/Viva.txt", "r"); //Le fichier texte qui contient la "partition"
    break;
    default:
    break;

}


   if (resultat != FMOD_OK)//verification que la musique marche
    {
        fprintf(stderr, "Impossible de lire le fichier audio.wav\n");
        exit(EXIT_FAILURE);
    }

//Bruit pour le fail (on est obligé de créer un autre systeme pour pas arreter la musique)
FMOD_SYSTEM *systemf;
FMOD_SOUND *fail = NULL;
FMOD_System_CreateSound(systemf, "fail.wav", FMOD_CREATESAMPLE, 0, &fail);
FMOD_RESULT resultatf;

    /* Création et initialisation d'un objet système */
    FMOD_System_Create(&systemf);
    FMOD_System_Init(systemf, 1, FMOD_INIT_NORMAL, NULL);

    /* Chargement du son et vérification du chargement */
    resultatf = FMOD_System_CreateSound(system, "fail.wav", FMOD_CREATESAMPLE, 0, &fail);
    if (resultatf != FMOD_OK)
    {
        fprintf(stderr, "Impossible de lire le fichier audio.wav\n");
        exit(EXIT_FAILURE);
    }

 /****************************
 Initialisation pour le texte
 ******************************/
    char caracteres[20] = "",caracteres2[20] = ""; // Tableau de char suffisamment grand pour le score
    TTF_Init(); //Initialisation de la banque de donnée pour le texte
    int compteur=0; //Pour le score
    SDL_Surface *score = NULL;
    SDL_Rect position;
    TTF_Font *police = NULL, *police2 = NULL; //TTF_OpenFont doit stocker son résultat dans une variable de type TTF_Font
    SDL_Color couleurNoire = {0, 0, 0}; //couleur police => noir
    police = TTF_OpenFont("police.ttf", 70);//police choisie, taille police
    police2 = TTF_OpenFont("score.ttf", 70);//police choisie, taille police
//////////////////////////////////////////////

 /***************************************************
        +Lecture du fichier texte (Yacine)
        +On met les notes a leur place (do,ré...)
            en fonction de la difficulté
 **************************************************/



char chaine[TAILLE_MAX]="";
int debut[TAILLE_MAX ];
int note[TAILLE_MAX ];
int tempsFin = 0 ;
 int j=0,compteurNotes=0;
 while (fgets(chaine, TAILLE_MAX, fichier) != NULL) //tant que le fichier n'a pas été totalement parcouru (fgets s'incremente automatiquement)
   {

        ///Easy
       if (difficulte==0){
    if (compteurNotes%3==0)//Pour la difficulté, on ne prend qu'une note sur 3 quand on a choisi l'option facile
            {
                sscanf(chaine, "%d - %d", &debut[j], &note[j]); // recupere la note et la date

switch (note[j])//On met en place les notes
{

   case 0 : //do
        positionNote[j].x = 250;
        break;
   case 1 : //ré
        positionNote[j].x = 395;
        break;
   case 2 : //mi
        positionNote[j].x = 525;
        break;
   case 3 : //fa
        positionNote[j].x = 680;
        break;
   case 4 : //sol
        positionNote[j].x = 820;
        break;
   case 5 : //la
        positionNote[j].x = 960;
        break;
   case 6 : //si
        positionNote[j].x = 1100;
        break;
    case 8 : // Pour la fin
        tempsFin = debut[j];
        positionNote[j].x = 20000;//pour pas afficher la note
   default :
        break;

        }
        j++;
            }
            compteurNotes++;
            }

        ///Normal
       if (difficulte==1){
    if (compteurNotes%2==0)//Pour la difficulté, on ne prend qu'une note sur deux quand on a choisi l'option facile
            {
                sscanf(chaine, "%d - %d", &debut[j], &note[j]); // recupere la note et la date

switch (note[j])//On met en place les notes
{

   case 0 : //do
        positionNote[j].x = 250;
        break;
   case 1 : //ré
        positionNote[j].x = 395;
        break;
   case 2 : //mi
        positionNote[j].x = 525;
        break;
   case 3 : //fa
        positionNote[j].x = 680;
        break;
   case 4 : //sol
        positionNote[j].x = 820;
        break;
   case 5 : //la
        positionNote[j].x = 960;
        break;
   case 6 : //si
        positionNote[j].x = 1100;
        break;
    case 8 : // Pour la fin
        tempsFin = debut[j];
        positionNote[j].x = 20000;//pour pas afficher la note
   default :
        break;

        }
        j++;
            }
            compteurNotes++;
            }

        ///Difficile
        if (difficulte==2){
            //On prend toutes les notes
                    sscanf(chaine, "%d - %d", &debut[j], &note[j]); // recupere la note et la date

switch (note[j])//On met en place les notes
{

   case 0 : //do
        positionNote[j].x = 250;
        break;
   case 1 : //ré
        positionNote[j].x = 395;
        break;
   case 2 : //mi
        positionNote[j].x = 525;
        break;
   case 3 : //fa
        positionNote[j].x = 680;
        break;
   case 4 : //sol
        positionNote[j].x = 820;
        break;
   case 5 : //la
        positionNote[j].x = 960;
        break;
   case 6 : //si
        positionNote[j].x = 1100;
        break;
    case 8 : // Pour la fin
        tempsFin = debut[j];
        positionNote[j].x = 20000;//pour pas afficher la note
   default :
        break;

        }
        j++;
            }


   }


 //////////////////////////////////////////////

int pourcent[TAILLE_MAX] = {0},pourcentFinal=0,totalNotes=0;//Pour le pourcentage de réussite
int k=0;//notes 1,2,3....
int tempsDebut=SDL_GetTicks();//SDL_GetTicks donne le temps qu'il s'est écoulé depuis le lancement du programme, on retire donc le temps qu'il s'est écoulé entre le lancement et le début du morceau
int a=0,z=0,e=0,r=0,t=0,y=0,u=0;//notes
int tempsPrecedent = 0, tempsActuel = 0, tempsNote[7]; //Timer (temps note permet de savoir a quel instant t la note a été jouée
int continuer = 1;

 //Boucle jeu

 if (ArduinoClavier) arduino(1);//On lance arduino pour avoir le numéro port série qui correspond

while (continuer)
{


/* On joue la musique au bon moment de manière à ce qu'elle soit synchronisée avec les notes qui défilent */
if ((tempsActuel>=2700)&&(tempsActuel<=2750))FMOD_System_PlaySound(system, FMOD_CHANNEL_FREE, musique, 0,NULL);


    /* On efface l'écran */
SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 255,255, 255));//255,255, 255 veut dire qu'on met un ecran noir
    /* On remet le fond */
SDL_BlitSurface(imageDeFond, NULL, ecran, &positionFond);

tempsActuel = SDL_GetTicks() - tempsDebut; //temps




/************************************************
 + On affiche les notes
 + On fait descendre les notes le long des lignes
    J'ai galeré pour ca !
*************************************************/


    if(tempsActuel>=debut[k+1]) k++; // passage à la note suivante



int l=k;

    do
    {
           if (tempsActuel>=debut[0]) positionNote[l].y= positionNote[l].y+tempsActuel/10*2-tempsPrecedent/10*2;//descente de la note en utilisant le temps comme réference (elle met du coup 2.7sec a desendre) (la condition corrige le bug de la 1ere note)

            if (positionNote[l].y>575) positionNote[l].y=10000; // si la note arrive en bas on la fait "disparaitre"

        SDL_BlitSurface(Note, NULL, ecran, &positionNote[l]);//on affiche les notes
        l--;
    }while(l>=0);



///La boucle do while est la car il faut la faire au moins une fois quand il n'y a qu'un seule note
///Pour afficher les notes précédentes (sinon on a qu'une seule note affichée)


/*Pour sortir du morceau à la fin*/
if (tempsActuel >= tempsFin) continuer = 0;



///


tempsPrecedent = tempsActuel; // comme on utilise le temps pour la boucle d'avant on le met ici (on pourrait le mettre à la toute fin, ce qui serait plus logique mais ici on comprend mieux)



/**************************************************************
*************************************************************
Fonction pour les touches
***********************************************************
**********************************************************/



/******************************************************
Switch pour savoir quelle touche a étée enfoncée. Si
une touche est enfoncée on donne a la variable la valeur
1 et on enregistre le temps a laquelle la note a été
"jouée"
*******************************************************/

SDL_PollEvent(&event);
switch(event.type)
{
case SDL_QUIT:
exit(EXIT_FAILURE);
break;
case SDL_KEYDOWN: /* Si appui sur une touche*/

    switch(event.key.keysym.sym)
    {
        case SDLK_q: //a
        a=1;
        tempsNote[0]=SDL_GetTicks() - tempsDebut;
        break;
        case SDLK_w: //z
        z=1;
        tempsNote[1]=SDL_GetTicks() - tempsDebut;
        break;
        case SDLK_e: //e
        e=1;
        tempsNote[2]=SDL_GetTicks() - tempsDebut;
        break;
        case SDLK_r: //r
        r=1;
        tempsNote[3]=SDL_GetTicks() - tempsDebut;
        break;
        case SDLK_t: //t
        t=1;
        tempsNote[4]=SDL_GetTicks() - tempsDebut;
        break;
        case SDLK_y: //y
        y=1;
        tempsNote[5]=SDL_GetTicks() - tempsDebut;
        break;
        case SDLK_u: //u
        u=1;
        tempsNote[6]=SDL_GetTicks() - tempsDebut;
        break;
        case SDLK_ESCAPE:
        continuer=0;
        break;
        default:
        break;
    }
break;

}




/*****************************************************************
On a donné à une variable la valeur 1 si l'evenement a été
réalisé, pour que deux évenements soient pris en compte en même
temps on laisse l'action que provoque l'evenement durer 250ms
(on utlise le temps enregistré avant pour savoir quand 250ms
 sont écoulées)
ce qui donne l'impression que les evenements sont simultannés
Si la variable=0, l'action n'est pas réalisée
******************************************************************/
if (a)
    {
        SDL_BlitSurface(Note_do, NULL, ecran, &positionNote_do);
        if(tempsActuel-tempsNote[0]>250) a=0;
    }
if (z)
    {
        SDL_BlitSurface(Note_re, NULL, ecran, &positionNote_re);
        if(tempsActuel-tempsNote[1]>250) z=0;
    }
if (e)
    {
        SDL_BlitSurface(Note_mi, NULL, ecran, &positionNote_mi);
        if(tempsActuel-tempsNote[2]>250) e=0;
    }
if (r)
    {
        SDL_BlitSurface(Note_fa, NULL, ecran, &positionNote_fa);
        if(tempsActuel-tempsNote[3]>250) r=0;
    }
if (t)
    {
        SDL_BlitSurface(Note_sol, NULL, ecran, &positionNote_sol);
        if(tempsActuel-tempsNote[4]>250) t=0;
    }
if (y)
    {
        SDL_BlitSurface(Note_la, NULL, ecran, &positionNote_la);
        if(tempsActuel-tempsNote[5]>250) y=0;
    }
if (u)
    {
        SDL_BlitSurface(Note_si, NULL, ecran, &positionNote_si);
        if(tempsActuel-tempsNote[6]>250) u=0;
    }


/*****************************************************************
Cette partie permet de déterminer quels boutons poussoirs sont enfoncés a partir du nombre
renvoyé par la fonction arduino.
Si un bouton est enfoncé on lui attribue un caractère propre, ainsi lors des tests de succès
cette information sera gérée exactement comme les évènements au clavier.


Bugs  incompréhensibles liés a l'ajout d'arduino:
On ne peux plus quitter la partie en cours (parfois si)
Au début de certains morceaux  des notes bizarres s'affichent
mais cela revient a la normale après 2-3 secondes.


                          Auteur : Yacine Saoudi
******************************************************************/

if (ArduinoClavier)
{

int arduinoIu=0;
arduinoIu=arduino(0);

char boutonArd[8];
sprintf(boutonArd, "%d", arduinoIu);
//on transforme le nombre stocké dans arduinoIu en chaine de caractère.

//cela permet de tester la présence ou non d'un caractère dans celle ci:
if(strstr(boutonArd, "1")!=NULL) a=1;
if(strstr(boutonArd, "2")!=NULL) z=1;
if(strstr(boutonArd, "3")!=NULL) e=1;
if(strstr(boutonArd, "4")!=NULL) r=1;
if(strstr(boutonArd, "5")!=NULL) t=1;
if(strstr(boutonArd, "6")!=NULL) y=1;
if(strstr(boutonArd, "7")!=NULL) u=1;

}



/***********************************************************************
Fonction réussit ou raté (si la note est "jouée" au bon moment)
************************************************************************/


l=k;//on teste toutes les notes qui on étées affichées

    do
    {
        //réussi
        if ((a)&&(positionNote[l].y>550)&&(positionNote[l].y<580)&&(positionNote[l].x == 250))  {compteur++; pourcent[l]=1;} //compteur => score
        if ((z)&&(positionNote[l].y>550)&&(positionNote[l].y<580)&&(positionNote[l].x == 395))  {compteur++; pourcent[l]=1;} //pourcent => la note spécifique l est réussie ou non (1= réussi)
        if ((e)&&(positionNote[l].y>550)&&(positionNote[l].y<580)&&(positionNote[l].x == 525))  {compteur++; pourcent[l]=1;}
        if ((r)&&(positionNote[l].y>550)&&(positionNote[l].y<580)&&(positionNote[l].x == 680))  {compteur++; pourcent[l]=1;}
        if ((t)&&(positionNote[l].y>550)&&(positionNote[l].y<580)&&(positionNote[l].x == 820))  {compteur++; pourcent[l]=1;}
        if ((y)&&(positionNote[l].y>550)&&(positionNote[l].y<580)&&(positionNote[l].x == 960))  {compteur++; pourcent[l]=1;}
        if ((u)&&(positionNote[l].y>550)&&(positionNote[l].y<580)&&(positionNote[l].x == 1100)) {compteur++; pourcent[l]=1;}
        //fail
        /*
        if ((a==0)&&(positionNote[l].y>560)&&(positionNote[l].y<570)&&(positionNote[l].x == 250)) FMOD_System_PlaySound(systemf, FMOD_CHANNEL_FREE, fail, 0, NULL);
        if ((z==0)&&(positionNote[l].y>560)&&(positionNote[l].y<570)&&(positionNote[l].x == 395)) FMOD_System_PlaySound(systemf, FMOD_CHANNEL_FREE, fail, 0, NULL);
        if ((e==0)&&(positionNote[l].y>560)&&(positionNote[l].y<570)&&(positionNote[l].x == 525)) FMOD_System_PlaySound(systemf, FMOD_CHANNEL_FREE, fail, 0, NULL);
        if ((r==0)&&(positionNote[l].y>560)&&(positionNote[l].y<570)&&(positionNote[l].x == 680)) FMOD_System_PlaySound(systemf, FMOD_CHANNEL_FREE, fail, 0, NULL);
        if ((t==0)&&(positionNote[l].y>560)&&(positionNote[l].y<570)&&(positionNote[l].x == 820)) FMOD_System_PlaySound(systemf, FMOD_CHANNEL_FREE, fail, 0, NULL);
        if ((y==0)&&(positionNote[l].y>560)&&(positionNote[l].y<570)&&(positionNote[l].x == 960)) FMOD_System_PlaySound(systemf, FMOD_CHANNEL_FREE, fail, 0, NULL);
        if ((u==0)&&(positionNote[l].y>560)&&(positionNote[l].y<570)&&(positionNote[l].x == 1100)) FMOD_System_PlaySound(systemf, FMOD_CHANNEL_FREE, fail, 0, NULL); //son de fausse note
        */
        l--;
    }while(l>=0); //j'aime bien les do while (mêmes raisons qu'au dessus)



/***********************************
Fonction pour le texte, ici le score
et le nom du morceau
************************************/

//En cas d'erreur (plus propre)
if(TTF_Init() == -1)
{

    fprintf(stderr, "Erreur d'initialisation de TTF_Init : %s\n", TTF_GetError());
    exit(EXIT_FAILURE);
}

/*score*/


     /* Écriture du texte dans la SDL_Surface texte en mode Solid (car il change souvent)*/
     sprintf(caracteres, "Score : %d", compteur);
     SDL_FreeSurface(score);//On efface la surface précédente (sinon ca prend 2go de RAM)
     score = TTF_RenderText_Solid(police, caracteres, couleurNoire);

    //Position score//
        position.x = 20;
        position.y = 450;
        SDL_BlitSurface(score, NULL, ecran, &position); /* Blit du texte*/

/*titre*/

   /* Titre en fonction du choix */
   switch (choix)
   {
       case 0 :
       sprintf(caracteres2, "Frère Jacques");
       break;
       case 1 :
       sprintf(caracteres2, "Starlight - Muse");
       break;
       case 2 :
       sprintf(caracteres2, "Au Clair de la Lune");
       break;
       case 3 :
       sprintf(caracteres2, "Titanic");
       break;
       case 4 :
       sprintf(caracteres2, "Black or White - MJ");
       break;
       case 5 :
       sprintf(caracteres2, "Clocks - Coldplay");
       break;
       case 6 :
       sprintf(caracteres2, "Laputa");
       break;
       case 7 :
       sprintf(caracteres2, "YMCA");
       break;
       case 8 :
       sprintf(caracteres2, "Changes");
       break;
       case 10 :
       sprintf(caracteres2, "Dancing in the Dark");
       break;
       case 11 :
       sprintf(caracteres2, "Born to Run");
       break;
       case 12 :
       sprintf(caracteres2, "Just the way you are");
       break;
       case 13 :
       sprintf(caracteres2, "Bad day");
       break;
       case 15 :
       sprintf(caracteres2, "The Fray");
       break;
       case 16 :
       sprintf(caracteres2, "Starway to heaven");
       break;
       case 17 :
       sprintf(caracteres2, "Naruto");
       break;
       case 18 :
       sprintf(caracteres2, "Somebody to love - Queen");
       break;
       case 19 :
       sprintf(caracteres2, "Viva la Vida - Coldplay");
       break;
       default :
       break;
   }

     SDL_FreeSurface(score);//On efface la surface précédente (sinon ca prend 2go de RAM)
     score = TTF_RenderText_Solid(police2, caracteres2, couleurNoire);

    //Position score//
        position.x = 20;
        position.y = 60;
        SDL_BlitSurface(score, NULL, ecran, &position); /* Blit du texte*/


////////////////////////////////////////////////////////////////////////////////////////

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

if (continuer==0) CloseCOM   ();//On ferme le port série
}

/******************************************************
Fonction pour obtenir le pourcentage de réussite
On utilise la variable pourcent (faire une vraie fonction
                                 de ca serait facile mais
                                 inutile)
Bug a corriger : Si on finit pas le morceau le pourcentage
est faux (narmol)
*****************************************************/

for(totalNotes=0;totalNotes<k;totalNotes++)
{
    if (pourcent[totalNotes]==1) pourcentFinal++;
}
 pourcentFinal=pourcentFinal*100/totalNotes;//on fait le pourcentage (il faut finir le morceau pour que le pourcentage soit juste)





///////////////////////////////////////////
/*Sortie de boucle*/
/////////////////////////////////////////
//Libération de l'espace
    //images
SDL_FreeSurface(imageDeFond);
SDL_FreeSurface(Note);
SDL_FreeSurface(Note_do);
SDL_FreeSurface(Note_re);
SDL_FreeSurface(Note_mi);
SDL_FreeSurface(Note_fa);
SDL_FreeSurface(Note_sol);
SDL_FreeSurface(Note_la);
SDL_FreeSurface(Note_si);
    //pour la musique
FMOD_Sound_Release(musique);
FMOD_Sound_Release(fail);
FMOD_System_Close(system);
FMOD_System_Release(system);

//return compteur;//le score (le pourcentage est plus interessant)
return pourcentFinal;//le pourcentage de réussite
}
Exemplo n.º 12
0
int main(int argc, char* args[])
{
	bool quit = false;
	
	if (!initialize())
	{
		return 1;
	}
	if (!loadFiles())
	{
		return 1;
	}
	
	Timer fps;
	Input input;
	
	// Prepare calculations to track the FPS.
	Timer fpsTrack, fpsTrackUpdate;
	int frame = 0;
	fpsTrack.start();
	fpsTrackUpdate.start();
	
	// Initalize map.
	Map map;
	map.load("maps/test.map");

	// Create character.
	Character character(0, 0, 32, 32, map);
	
	// Handle player input.
	input.input();
	
	// Start main game loop.
	while (!quit)
	{
		fps.start(); // Update FPS counter.
		
		while (SDL_PollEvent(&event))
		{
			// Check for quit.
			if (event.type == SDL_QUIT)
			{
				quit = true; // Quit loop.
			}
		}
		
		// Fill the screen with a background color.
		SDL_FillRect(screen, &screen->clip_rect, SDL_MapRGB(screen->format, 0xac, 0xc6, 0xd7));
		
		// Draw map tiles.
		map.draw();
		
		// Move character according to inputs and collision.
		//std::cout << character.getX() << " " << character.getY() << " " << character.getYVel() << "\n";
		character.move(&input);
		
		// Draw character.
		character.draw();
		
		// Flip screen.
		if (SDL_Flip(screen) == -1)
		{
			return 1;
		}
		frame++;
		
		// Display the realtime FPS.
		//if (fpsTrackUpdate.get() > 1000)
		//{
		//	std::cout << frame / (fpsTrack.get()/1000.f) << "\n";
			
		//	fpsTrackUpdate.start(); // Reset fpsTrackUpdate. We only want to periodically get the FPS.
		//}
		
		// Regulate frames.
		int fpsDiv = 1000/FPS;
		if (fps.get() < fpsDiv)
		{
			SDL_Delay(fpsDiv - fps.get());
		}
	}
	
	// Clean up used resources.
	cleanUp();
	
	return 0;
}
Exemplo n.º 13
0
int main(int argc, char *argv[]) {
    /* Declare some variables */
    SNDFILE *music_file = NULL;
    SF_INFO sfinfo;
    sfinfo.format = 0;

    printf("Audio visualizer for Comp 467\n");
    printf("By: Jorenz Paragas, Carlos Henriquez, Joshua Licudo\n");
    printf("----\n");

    /* Check if the user provided a .wav file */
    if (argc < 2) {
        fprintf(stderr, "Error: a .wav file was not provided.\n");
        fprintf(stderr, "Usage: %s input.wav\n", argv[0]);
        return EXIT_FAILURE;
    }

    /* Open the .wav file */
    music_file = sf_open(argv[1], SFM_READ, &sfinfo);
    if (music_file == NULL) {
        fprintf(stderr, "Cannot open .wav file: %s\n", argv[1]);
        return EXIT_FAILURE;
    }

    printf("Name of file: %s\n", argv[1]);
    printf("Sample rate: %d\n", sfinfo.samplerate);
    printf("Channels: %d\n", sfinfo.channels);

    /* The buffer size for libsndfile must be as large as the product of
     * the number of channels and the number of samples to be read */ 
    const int buffer_size = SAMPLE_COUNT * sfinfo.channels;

    /* For a real-to-complex transform, according to the FFTW docs,
     * the expected size of the array is n / 2 + 1 */
    const int out_buffer_size = buffer_size / 2 + 1;

    /* Declare the two buffers to hold the data and tell
     * FFTW how to calculate the frequencies */
    double samples[buffer_size];
    memset(&samples, 0, buffer_size);

    fftw_complex output[out_buffer_size];
    fftw_plan plan = fftw_plan_dft_r2c_1d(buffer_size, samples, 
        output, FFTW_ESTIMATE);

    if (plan == NULL) {
        fprintf(stderr, "Plan cannot be created.\n");
        sf_close(music_file);
        return EXIT_FAILURE;
    }

    /* Start SDL */
    if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {
        fprintf(stderr, "SDL_Init error: %s\n", SDL_GetError());
        return EXIT_FAILURE;
    }
    atexit(SDL_Quit);

    /* Create the window */
    SDL_Window *window = SDL_CreateWindow("Comp 467 Project", 10, 10, 
        WINDOW_WIDTH, WINDOW_HEIGHT, 0);
    if (window == NULL) {
        fprintf(stderr, "SDL_CreateWindow error: %s\n", SDL_GetError());
        return EXIT_FAILURE;
    }
    
    /* Get the window's surface */
    SDL_Surface *surface = SDL_GetWindowSurface(window);
    
    /* Initialize the random number generator */
    srand(time(NULL));

    /* Open the music file */
    Mix_OpenAudio(sfinfo.samplerate, MIX_DEFAULT_FORMAT, 
        sfinfo.channels, 4096);
    Mix_Music *music = Mix_LoadMUS(argv[1]);
    if (music == NULL) {
        fprintf(stderr, "Mix_LoadMUS error: %s\n", Mix_GetError());
    }
    
    /* Start playing it */
    Mix_PlayMusic(music, 0);

    /* Timer-related variables */
    unsigned int start_time = SDL_GetTicks();
    unsigned int last_time = start_time;
    unsigned int current_time = start_time;

    /* The main loop */
    bool running = true;
    while (running) {
        /* Obtain any user input */
        SDL_Event event;
        while (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                running = false;
            }
        }

        /* Based on the sample rate and the current time,
         * figure out what position to read the audio file from */
        double seconds = (current_time - start_time) / 1000.0; 
        //printf("Current time: %.2f\n", seconds);

        sf_count_t sample_pos = (int) sfinfo.samplerate * seconds; 
        int result = sf_seek(music_file, sample_pos, SEEK_SET);
        if (result == -1) {
            running = false;
        }

        /* Read the samples */
        int samples_read = sf_readf_double(music_file, samples, 
            SAMPLE_COUNT); 
        if (samples_read <= 0) {
            running = false;        
        }
    
        /* Calculate the FFT */
        fftw_execute(plan);

        /* Fill the screen with black first */
        SDL_Rect surf_rect;
        
        surf_rect.w = WINDOW_WIDTH;
        surf_rect.h = WINDOW_HEIGHT;

        surf_rect.x = 0;
        surf_rect.y = 0;

        SDL_FillRect(surface, &surf_rect, SDL_MapRGB(surface->format,
                     0, 0, 0));

        /* Draw all the rectangles */
        int x_pos;
        for (x_pos = 0; x_pos < WINDOW_WIDTH; x_pos += 1) {
            SDL_Rect rect;

            /* Based on the rectangle's position, get a different
             * frequency; the second half of the buffer is useless
             * data, so ignore that portion */
            double relative_pos = x_pos * 1.0f / WINDOW_WIDTH; 
            int buf_range_max = out_buffer_size / 2;
            int index = (int) (relative_pos * buf_range_max);

            /* Figure out the normalized magnitude of the frequency */
            double mag = sqrt(output[index][0] * output[index][0] +
                              output[index][1] * output[index][1]);
            double norm_mag = mag * (1 / sqrt(buffer_size)); 
            //printf("%d: %f\n", index, norm_mag);

            /* Set the rectangle's size */
            rect.w = 1;
            rect.h = norm_mag * WINDOW_HEIGHT;

            /* Set the rectangle's lower left corner */
            rect.x = x_pos;
            rect.y = WINDOW_HEIGHT - rect.h;

            /* Draw the rectangle to the screen */
            SDL_FillRect(surface, &rect, SDL_MapRGB(surface->format,
                         0, 0, 255));
        }

        /* Update the display */
        SDL_UpdateWindowSurface(window);

        /* Ensure that it runs around 30 FPS and also update the
         * timer variables */ 
        current_time = SDL_GetTicks();
        int delta = current_time - last_time;
        if (delta <= 33) {
            SDL_Delay(33 - delta);
        }
        last_time = current_time;
    }

    /* Stop the music and free its memory */
    Mix_HaltMusic();
    Mix_FreeMusic(music);

    /* Clean up and exit */
    SDL_FreeSurface(surface);
    SDL_DestroyWindow(window);

    fftw_destroy_plan(plan);
    sf_close(music_file);

    return EXIT_SUCCESS;
}
Exemplo n.º 14
0
void clearScreen()
{
	SDL_FillRect(screen, NULL, SDL_MapRGB(screen->format, 0, 0, 0));
}
Exemplo n.º 15
0
/*
====================================================================
Load a SHP file to a PG_Shp struct.
Since SHP files are only found in source path (=original PG data),
for simplicity this function only gets the file name and the 
source_path is always prepended for opening the file.
====================================================================
*/
PG_Shp *shp_load( const char *fname )
{
    int i;
    FILE *file = 0;
    char path[MAXPATHLEN];
    int dummy;
    int width = 0, height = 0;
    int old_pos, pos, pal_pos;
    PG_Shp *shp = 0; 
    SDL_PixelFormat *pf = SDL_GetVideoSurface()->format;
    Uint32 ckey = MAPRGB( CKEY_RED, CKEY_GREEN, CKEY_BLUE ); /* transparent color key */
    Icon_Header header;
    RGB_Entry pal[256];
    RGB_Entry *actual_pal = 0;
    int icon_maxw = 60, icon_maxh = 50;
    
    snprintf( path, MAXPATHLEN, "%s/%s", source_path, fname );
    if ( ( file = fopen_ic( path, "r" ) ) == NULL ) {
        printf("Could not open file %s\n",path);
        return NULL;
    }   
    
    /* magic */
    fread( &dummy, 4, 1, file );
    /* shp struct */
    shp = calloc( 1, sizeof( PG_Shp ) );
    /* icon count */
    fread( &shp->count, 4, 1, file );
    shp->count = SDL_SwapLE32(shp->count);
    if ( shp->count == 0 ) {
        fprintf( stderr, "%s: no icons found\n", path );
        goto failure;
    }
    /* create surface (measure size first) */
    for ( i = 0; i < shp->count; i++ ) {
        /* read file position of actual data and palette */
        fread( &pos, 4, 1, file );
        pos = SDL_SwapLE32(pos);
        fread( &dummy, 4, 1, file );
        old_pos = ftell( file );
        /* read header */
        fseek( file, pos, SEEK_SET );
        shp_read_icon_header( file, &header );
        /* XXX if icon is too large, ignore it and replace with an empty
         * icon of maximum size; use hardcoded limit which is basically okay
         * as we convert PG data and can assume the icons have size of map
         * tile at maximum. */
        if ( header.width > icon_maxw || header.height > icon_maxh ) {
            fprintf( stderr, "Icon %d in %s is too large (%dx%d), replacing "
                                        "with empty icon\n", i, fname, 
                                        header.width,header.height  );
            header.width = icon_maxw;
            header.height = icon_maxh;
            header.valid = 0;
        }
        if ( header.width > width )
            width = header.width;
        height += header.height;
        fseek( file, old_pos, SEEK_SET );
    }
    shp->surf = SDL_CreateRGBSurface( SDL_SWSURFACE, width, height, pf->BitsPerPixel, pf->Rmask, pf->Gmask, pf->Bmask, pf->Amask );
    if ( shp->surf == 0 ) {
        fprintf( stderr, "error creating surface: %s\n", SDL_GetError() );
        goto failure;
    }
    SDL_FillRect( shp->surf, 0, ckey );
    /* read icons */
    shp->offsets = calloc( shp->count, sizeof( int ) );
    shp->headers = calloc( shp->count, sizeof( Icon_Header ) );
    fseek( file, 8, SEEK_SET );
    for ( i = 0; i < shp->count; i++ ) {
        /* read position of data and palette */
        pos = pal_pos = 0;
        fread( &pos, 4, 1, file );
        pos = SDL_SwapLE32(pos);
        fread( &pal_pos, 4, 1, file );
        pal_pos = SDL_SwapLE32(pal_pos);
        old_pos = ftell( file );
        /* read palette */
        if ( !use_def_pal && pal_pos > 0 ) {
            fseek( file, pal_pos, SEEK_SET );
            shp_read_palette( file, pal );
            actual_pal = pal;
        }
        else
            actual_pal = def_pal;
        /* read header */
        fseek( file, pos, SEEK_SET );
        shp_read_icon_header( file, &header );
        /* see comment in measure loop above; have empty icon if too large */
        if ( header.width > icon_maxw || header.height > icon_maxh ) {
            /* error message already given in measure loop */
            header.width = icon_maxw;
            header.height = icon_maxh;
            header.valid = 0;
        }
        if ( header.valid )
            shp_read_icon( file, shp->surf, shp->offsets[i], actual_pal, &header );
        if ( i < shp->count - 1 )
            shp->offsets[i + 1] = shp->offsets[i] + header.height;
        memcpy( &shp->headers[i], &header, sizeof( Icon_Header ) );
        fseek( file, old_pos, SEEK_SET );
    }
    fclose( file );
    return shp;
failure:
    if ( file ) fclose( file );
    if ( shp ) shp_free( &shp );
    return 0;
}
Exemplo n.º 16
0
int main(int argc, char *argv[])
{
    SDL_Surface *ecran = NULL, *menu = NULL, *manuel = NULL;
    SDL_Rect positionMenu;
    SDL_Event event;

    int continuer = 1, afficherManuel = 0;

    SDL_Init(SDL_INIT_VIDEO);

    SDL_WM_SetIcon(IMG_Load("caisse.jpg"), NULL); // L'ic�ne doit �tre charg�e avant SDL_SetVideoMode
    ecran = SDL_SetVideoMode(408, 408, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
    //ecran = SDL_SetVideoMode(LARGEUR_FENETRE, HAUTEUR_FENETRE, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
    SDL_WM_SetCaption("Naruto Sokoban", NULL);

    menu = IMG_Load("menu.png");
    manuel = IMG_Load("GFX/manuel.png");
    positionMenu.x = 0;
    positionMenu.y = 0;

    while (continuer)
    {
        SDL_WaitEvent(&event);
        switch(event.type)
        {
            case SDL_QUIT:
                continuer = 0;
                break;
            case SDL_KEYDOWN:
                switch(event.key.keysym.sym)
                {
                    case SDLK_ESCAPE: // Veut arr�ter le jeu
                        if (afficherManuel != 1)
                        {
                            continuer = 0;
                        }
                        else
                        {
                            afficherManuel = 0;
                        }
                        break;
                    case SDLK_1: // Demande � jouer
                        if (afficherManuel != 1)
                        {
                            menuNiveau(ecran, 1);
                        }
                        else
                        {
                            afficherManuel = 0;
                        }
                        break;
                    case SDLK_2: // Demande l'�diteur de niveaux
                        if (afficherManuel != 1)
                        {
                        menuNiveau(ecran, 0);
                        }
                        else
                        {
                            afficherManuel = 0;
                        }
                        break;
                    case SDLK_3:
                        //afficher image avec les r�gles
                        if (afficherManuel == 0)
                        {
                            afficherManuel = 1;
                        }
                        else
                        {
                            afficherManuel = 0;
                        }
                        break;
                }
                break;
        }

        // Effacement de l'�cran
        ecran = SDL_SetVideoMode(408, 408, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);

        SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 0, 0, 0));
        if (afficherManuel == 1)
        {
            SDL_BlitSurface(manuel, NULL, ecran, &positionMenu);
        }
        else
        {
            SDL_BlitSurface(menu, NULL, ecran, &positionMenu);
        }
        SDL_Flip(ecran);
    }

    SDL_FreeSurface(menu);
    SDL_FreeSurface(manuel);
    SDL_Quit();

    return EXIT_SUCCESS;
}
Exemplo n.º 17
0
SDL_Surface *
SDL_SetVideoMode(int width, int height, int bpp, Uint32 flags)
{
    SDL_DisplayMode desktop_mode;
    int display = GetVideoDisplay();
    int window_x = SDL_WINDOWPOS_UNDEFINED_DISPLAY(display);
    int window_y = SDL_WINDOWPOS_UNDEFINED_DISPLAY(display);
    int window_w;
    int window_h;
    Uint32 window_flags;
    Uint32 surface_flags;

    if (!SDL_GetVideoDevice()) {
        if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0) {
            return NULL;
        }
    }

    SDL_GetDesktopDisplayMode(display, &desktop_mode);

    if (width == 0) {
        width = desktop_mode.w;
    }
    if (height == 0) {
        height = desktop_mode.h;
    }
    if (bpp == 0) {
        bpp = SDL_BITSPERPIXEL(desktop_mode.format);
    }

    /* See if we can simply resize the existing window and surface */
    if (SDL_ResizeVideoMode(width, height, bpp, flags) == 0) {
        return SDL_PublicSurface;
    }

    /* Destroy existing window */
    SDL_PublicSurface = NULL;
    if (SDL_ShadowSurface) {
        SDL_ShadowSurface->flags &= ~SDL_DONTFREE;
        SDL_FreeSurface(SDL_ShadowSurface);
        SDL_ShadowSurface = NULL;
    }
    if (SDL_VideoSurface) {
        SDL_VideoSurface->flags &= ~SDL_DONTFREE;
        SDL_FreeSurface(SDL_VideoSurface);
        SDL_VideoSurface = NULL;
    }
    if (SDL_VideoContext) {
        /* SDL_GL_MakeCurrent(0, NULL); *//* Doesn't do anything */
        SDL_GL_DeleteContext(SDL_VideoContext);
        SDL_VideoContext = NULL;
    }
    if (SDL_VideoWindow) {
        SDL_GetWindowPosition(SDL_VideoWindow, &window_x, &window_y);
        SDL_DestroyWindow(SDL_VideoWindow);
    }

    /* Set up the event filter */
    if (!SDL_GetEventFilter(NULL, NULL)) {
        SDL_SetEventFilter(SDL_CompatEventFilter, NULL);
    }

    /* Create a new window */
    window_flags = SDL_WINDOW_SHOWN;
    if (flags & SDL_FULLSCREEN) {
        window_flags |= SDL_WINDOW_FULLSCREEN;
    }
    if (flags & SDL_OPENGL) {
        window_flags |= SDL_WINDOW_OPENGL;
    }
    if (flags & SDL_RESIZABLE) {
        window_flags |= SDL_WINDOW_RESIZABLE;
    }
    if (flags & SDL_NOFRAME) {
        window_flags |= SDL_WINDOW_BORDERLESS;
    }
    GetEnvironmentWindowPosition(width, height, &window_x, &window_y);
    SDL_VideoWindow =
        SDL_CreateWindow(wm_title, window_x, window_y, width, height,
                         window_flags);
    if (!SDL_VideoWindow) {
        return NULL;
    }
    SDL_SetWindowIcon(SDL_VideoWindow, SDL_VideoIcon);

    SetupScreenSaver(flags);

    window_flags = SDL_GetWindowFlags(SDL_VideoWindow);
    surface_flags = 0;
    if (window_flags & SDL_WINDOW_FULLSCREEN) {
        surface_flags |= SDL_FULLSCREEN;
    }
    if ((window_flags & SDL_WINDOW_OPENGL) && (flags & SDL_OPENGL)) {
        surface_flags |= SDL_OPENGL;
    }
    if (window_flags & SDL_WINDOW_RESIZABLE) {
        surface_flags |= SDL_RESIZABLE;
    }
    if (window_flags & SDL_WINDOW_BORDERLESS) {
        surface_flags |= SDL_NOFRAME;
    }

    SDL_VideoFlags = flags;

    /* If we're in OpenGL mode, just create a stub surface and we're done! */
    if (flags & SDL_OPENGL) {
        SDL_VideoContext = SDL_GL_CreateContext(SDL_VideoWindow);
        if (!SDL_VideoContext) {
            return NULL;
        }
        if (SDL_GL_MakeCurrent(SDL_VideoWindow, SDL_VideoContext) < 0) {
            return NULL;
        }
        SDL_VideoSurface =
            SDL_CreateRGBSurfaceFrom(NULL, width, height, bpp, 0, 0, 0, 0, 0);
        if (!SDL_VideoSurface) {
            return NULL;
        }
        SDL_VideoSurface->flags |= surface_flags;
        SDL_PublicSurface = SDL_VideoSurface;
        return SDL_PublicSurface;
    }

    /* Create the screen surface */
    SDL_WindowSurface = SDL_GetWindowSurface(SDL_VideoWindow);
    if (!SDL_WindowSurface) {
        return NULL;
    }

    /* Center the public surface in the window surface */
    SDL_GetWindowSize(SDL_VideoWindow, &window_w, &window_h);
    SDL_VideoViewport.x = (window_w - width)/2;
    SDL_VideoViewport.y = (window_h - height)/2;
    SDL_VideoViewport.w = width;
    SDL_VideoViewport.h = height;

    SDL_VideoSurface = SDL_CreateRGBSurfaceFrom(NULL, 0, 0, 32, 0, 0, 0, 0, 0);
    SDL_VideoSurface->flags |= surface_flags;
    SDL_VideoSurface->flags |= SDL_DONTFREE;
    SDL_FreeFormat(SDL_VideoSurface->format);
    SDL_VideoSurface->format = SDL_WindowSurface->format;
    SDL_VideoSurface->format->refcount++;
    SDL_VideoSurface->w = width;
    SDL_VideoSurface->h = height;
    SDL_VideoSurface->pitch = SDL_WindowSurface->pitch;
    SDL_VideoSurface->pixels = (void *)((Uint8 *)SDL_WindowSurface->pixels +
        SDL_VideoViewport.y * SDL_VideoSurface->pitch +
        SDL_VideoViewport.x  * SDL_VideoSurface->format->BytesPerPixel);
    SDL_SetClipRect(SDL_VideoSurface, NULL);

    /* Create a shadow surface if necessary */
    if ((bpp != SDL_VideoSurface->format->BitsPerPixel)
        && !(flags & SDL_ANYFORMAT)) {
        SDL_ShadowSurface =
            SDL_CreateRGBSurface(0, width, height, bpp, 0, 0, 0, 0);
        if (!SDL_ShadowSurface) {
            return NULL;
        }
        SDL_ShadowSurface->flags |= surface_flags;
        SDL_ShadowSurface->flags |= SDL_DONTFREE;

        /* 8-bit SDL_ShadowSurface surfaces report that they have exclusive palette */
        if (SDL_ShadowSurface->format->palette) {
            SDL_ShadowSurface->flags |= SDL_HWPALETTE;
            SDL_DitherColors(SDL_ShadowSurface->format->palette->colors,
                             SDL_ShadowSurface->format->BitsPerPixel);
        }
        SDL_FillRect(SDL_ShadowSurface, NULL,
            SDL_MapRGB(SDL_ShadowSurface->format, 0, 0, 0));
    }
    SDL_PublicSurface =
        (SDL_ShadowSurface ? SDL_ShadowSurface : SDL_VideoSurface);

    ClearVideoSurface();

    /* We're finally done! */
    return SDL_PublicSurface;
}
Exemplo n.º 18
0
int Game::run()
{
    if (!_state) {
        fprintf(stderr, "No state provided \n");
        return -1;
    }

    if (_failtype < 0)
        return _failtype;

    while(Globals::_running) {
#if defined(SDL_VIDEO)
        while(SDL_PollEvent(&_event)) {
            switch(_event.type) {
                case SDL_QUIT:
                    Globals::quit();
#ifdef DEBUG
                    fprintf(stdout, "Quit pressed\n");
#endif
                    break;
                case SDL_KEYUP:
                    Globals::keys.setKeyState(Keyboard::Key::State::RELEASED, _event.key.keysym.sym);
                    break;
                case SDL_KEYDOWN:
                    Globals::keys.setKeyState(Keyboard::Key::State::PRESSED, _event.key.keysym.sym);
                    break;
                case SDL_MOUSEMOTION:
                    Globals::mouse.setMousePos(_event.motion.x, _event.motion.y);
                    break;
                case SDL_MOUSEBUTTONUP:
                    Globals::mouse.setButtonState(SDL_MOUSEBUTTONUP, _event.button.button);
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    Globals::mouse.setButtonState(SDL_MOUSEBUTTONDOWN, _event.button.button);
                    break;
            }
        }

#elif  defined(X11_VIDEO) && defined(HW_RENDER)
        while(XPending(_GLWin.dpy) > 0)
        {   
            XNextEvent(_GLWin.dpy, &_event);
            switch(_event.type)
            {   
                case Expose:
                    if (_event.xexpose.count != 0)
                        break;

#ifdef DEBUG
                    fprintf(stdout, "Expose\n");
#endif
                    break;
                case ConfigureNotify:
                    if ((_event.xconfigure.width  != (signed) _GLWin.width) ||
                            (_event.xconfigure.height != (signed) _GLWin.height))
                    {   
                        _GLWin.width  = _event.xconfigure.width;
                        _GLWin.height = _event.xconfigure.height;

#ifdef DEBUG
                        fprintf(stdout, "Resize Event\n");
#endif                              
                    }   
                    break;
                case KeyPress:
                    Globals::keys.setKeyState(Keyboard::Key::State::PRESSED, XLookupKeysym(&_event.xkey,0));
                    break;
                case KeyRelease:
                    {
                        KeyCode key = XLookupKeysym(&_event.xkey,0);
                        if(key != 0)
                            Globals::keys.setKeyState(Keyboard::Key::State::RELEASED, key);
                    }
                    break;
                case ClientMessage:
                    if (*XGetAtomName(_GLWin.dpy, _event.xclient.message_type) == *"WM_PROTOCOLS")
                    {   
#ifdef DEBUG
                        fprintf(stdout, "Quit pressed\n");
#endif
                        Globals::quit();
                    }   
                    break;
                default:
                    break;
            }   
        }   
#endif

        if(_state) {
            _state->update();
            _state->render();
        } else {
            fprintf(stderr, "State not found\n");
        }

#if defined(X11_VIDEO) && defined(HW_RENDER)
        if(_GLWin.doublebuffer)
            glXSwapBuffers(_GLWin.dpy, _GLWin.win);
        else
            glFlush();

        glClearColor( (float) RED_FROM_UI32(State::bgColor)   / 255,
                      (float) GREEN_FROM_UI32(State::bgColor) / 255,
                      (float) BLUE_FROM_UI32(State::bgColor)  / 255,
                      (float) ALPHA_FROM_UI32(State::bgColor) / 255);

        glClear(GL_COLOR_BUFFER_BIT);
        glLoadIdentity();
#elif defined(SDL_VIDEO) && defined(HW_RENDER)
        SDL_GL_SwapBuffers();

        glClearColor( (float) RED_FROM_UI32(State::bgColor)   / 255,
                      (float) GREEN_FROM_UI32(State::bgColor) / 255,
                      (float) BLUE_FROM_UI32(State::bgColor)  / 255,
                      (float) ALPHA_FROM_UI32(State::bgColor) / 255);

        glClear(GL_COLOR_BUFFER_BIT);
        glLoadIdentity();
#elif defined(SDL_VIDEO) && defined(SW_RENDER)
        SDL_BlitSurface(Globals::_buffer, 0, _screen, 0);
        SDL_UpdateRect(_screen, 0,0,0,0);
        SDL_FillRect(Globals::_buffer,0, State::bgColor);
#endif

        unsigned int now;
        _frametime = 0;

        do {
            timeb tb;
            ftime( &tb );
            now = tb.millitm + (tb.time & 0xfffff) * 1000;
            _frametime = (now > _lasttime) ? now - _lasttime : 0;
            _lasttime  = (now >= _lasttime) ? _lasttime : now;
        } while(!(_frametime >= minFPS));

        if(_frametime > maxFPS)
            _frametime = maxFPS;

        _timeaccum += _frametime;
        _framecount++;
        _elapsed = (float) _frametime * 0.001f;

        if(_timeaccum >= 1000) {
            Globals::FPS = _frametime;
            _framecount   = 0;
            _timeaccum    = 0;
        }

        Globals::elapsed = _elapsed;
        _lasttime = now;
    }

    return 0;
}
Exemplo n.º 19
0
void COpenGL::updateScreen()
{
	glEnable(GL_TEXTURE_2D);
	// Set up an array of values to use as the sprite vertices.
	GLfloat vertices[] =
	{
		0, 0,
		1, 0,
		1, 1,
		0, 1,
	};

	// Set up an array of values for the texture coordinates.
	GLfloat texcoords[] =
	{
		0, 0,
		1, 0,
		1, 1,
		0, 1,
	};

	//Render the vertices by pointing to the arrays.
    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_TEXTURE_COORD_ARRAY);

	glVertexPointer(2, GL_FLOAT, 0, vertices);
	glTexCoordPointer(2, GL_FLOAT, 0, texcoords);

	glEnable(GL_BLEND);

	if(m_VidConfig.m_ScaleXFilter > 1)
	{
		SDL_BlitSurface(FGLayerSurface, NULL, BlitSurface, NULL);

		if(getPerSurfaceAlpha(FXSurface))
			SDL_BlitSurface(FXSurface, NULL, BlitSurface, NULL);
	}

	loadSurface(m_texture, BlitSurface);
	renderTexture(m_texture);


	if(m_VidConfig.m_ScaleXFilter == 1)
	{
		if(FGLayerSurface)
		{
			reloadFG(FGLayerSurface);
			renderTexture(m_texFG, true);
		}

		if(FXSurface && getPerSurfaceAlpha(FXSurface))
		{
			reloadFX(FXSurface);
			renderTexture(m_texFX, true);
		}
	}

	glDisableClientState(GL_VERTEX_ARRAY);
	glDisableClientState(GL_TEXTURE_COORD_ARRAY);
	glDisable(GL_BLEND);
	glDisable(GL_TEXTURE_2D);

	g_pInput->renderOverlay();

	SDL_GL_SwapBuffers();

	// Flush the FG-Layer
	if(m_VidConfig.m_ScaleXFilter == 1)
		SDL_FillRect(FGLayerSurface, NULL, SDL_MapRGBA(FGLayerSurface->format, 0, 0, 0, 0));
	else
		SDL_FillRect(FGLayerSurface, NULL, SDL_MapRGB(FGLayerSurface->format, 0, 0xFF, 0xFE));
}
Exemplo n.º 20
0
/**
 * Fill a rectangle on a given surface. Alias for SDL_FillRect.
 *
 * @param dst                     The surface to operate on.
 * @param dst_rect                The rectangle to fill.
 * @param color                   Color of the rectangle.
 */
inline void fill_rect(surface& dst, SDL_Rect* dst_rect, const Uint32 color)
{
	SDL_FillRect(dst, dst_rect, color);
}
Exemplo n.º 21
0
void MasterController::gameLoop() {
	scale = new Scale();
	//Set scale here!!!
	scale->set(1.f, 1.f);

	ballSimulation = new BallSimulation();
	ballSimulation->init();

	ballView = new BallView(ballSimulation);
	boarderView = new BoarderView();

	SDL_Init(SDL_INIT_EVERYTHING);

	window = SDL_CreateWindow("BouncingBall", 400, 200, screenWidth * scale->getW(), screenHeight * scale->getH(), SDL_WINDOW_RESIZABLE | SDL_WINDOW_SHOWN);
	render = SDL_CreateRenderer(window, 0, 0);
	surfaceScreen = SDL_GetWindowSurface(window);

	surfaceBall = ballSimulation->loadImage("ball.png", *surfaceScreen);
	if (surfaceBall == NULL) {
		printf("could not get ball image");
	}

	Uint64 frequency = SDL_GetPerformanceFrequency();
	Uint64 thisTick = SDL_GetPerformanceCounter();
	Uint64 lastTick = thisTick;
	float deltaTime;

	float h;
	float w;

	bool running = 1;
	while (running) {
		while (SDL_PollEvent(&event)) {
			if (event.type == SDL_QUIT) {
				running = 0;
			} else if (event.type == SDL_WINDOWEVENT) {
				if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
					//Rezise window
					surfaceScreen = SDL_GetWindowSurface(window);

					//calculate new scaling.
					h = surfaceScreen->h - surfaceOldScreen->h + surfaceOldScreen->h;
					w = surfaceScreen->w - surfaceOldScreen->w + surfaceOldScreen->w;
					
					w = abs(w);
					h = abs(h);
					
					w /= 1000;
					h /= 1000;

					if (w == 0) {
						w = scale->getW();
					} else if (h == 0) {
						h = scale->getH();;
					} 

					scale->set(w, h);
				}
			} else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) {
				running = 0;
			} else {
				surfaceOldScreen = SDL_GetWindowSurface(window);
			}
		}

		// Clear screen
		SDL_FillRect(surfaceScreen, NULL, 0);

		thisTick = SDL_GetPerformanceCounter();
		// Delta time in milliseconds.
		deltaTime = ((float)(thisTick - lastTick) / (float)frequency) * 1000.0f;
		lastTick = thisTick;

		// Render game board
		rectArea = boarderView->getPlayArea(window, border * scale->getW(), border * scale->getH());
		boarderView->renderBorder(surfaceScreen, rectArea);

		//draw ball.
		rectBall = ballView->drawBall(deltaTime, rectArea, scale->getH(), scale->getW());
		FillRectBall(rectBall.x, rectBall.y, rectBall.w, rectBall.h);

		SDL_UpdateWindowSurface(window);
		SDL_Delay(0);
	}

	//Free memory.
	SDL_FreeSurface(surfaceScreen);
	SDL_FreeSurface(surfaceBall);

	freeMem();

	SDL_DestroyWindow(window);
	SDL_Quit();
}
Exemplo n.º 22
0
/*Cette fonction sert de page d'accueil du jeu du Pendu, elle fait appel à la fonction jouer_Pendu quand l'utilisateur
  appuie sur "Entrer", et à la fin elle récupère l'indice du gagnant et le renvoie à son tour*/
int Accueil_Pendu(SDL_Surface *ecran, char *j1, char *j2) {
  //Déclaration des variables locales nécessaires pour la fonction.
  SDL_Surface *texte1 = NULL, *texte2 = NULL, *pendu = NULL;
  SDL_Rect positiontexte1, positiontexte2, positionpendu;
  SDL_Event event;
  TTF_Font *police1 = NULL, *police2 = NULL;
  SDL_Color couleurNoire = {0, 0, 0, 0}, couleurBlanche = {255, 255, 255, 0};
  int continuer = 1, gagnant;
  Mix_Music *musique; //Création d'un pointeur de type Mix_Music
  Mix_VolumeMusic(MIX_MAX_VOLUME);
  musique = Mix_LoadMUS("../Music/Mini-jeux/pendu.ogg"); //Chargement de la musique
  Mix_PlayMusic(musique, -1); //Jouer infiniment la musique

  //Chargement de l'image du pendu
  pendu = IMG_Load("../images/Mini-jeux/Pendu10.png");

  //Chargement de la police
  police1 = TTF_OpenFont("../Police/chata.ttf", 65);
  police2 = TTF_OpenFont("../Police/chata.ttf", 25);

  //Initialisation du texte
  texte1 = TTF_RenderText_Shaded(police1, "Le Pendu", couleurNoire, couleurBlanche);
  texte2 = TTF_RenderText_Shaded(police2, "Appuyer sur entrer pour commencer", couleurNoire, couleurBlanche);

  SDL_SetColorKey(texte1, SDL_SRCCOLORKEY, SDL_MapRGB(texte1->format, 255, 255, 255));
  SDL_SetColorKey(texte2, SDL_SRCCOLORKEY, SDL_MapRGB(texte2->format, 255, 255, 255));

  //Remplissage de l'écran principal avec la couleur blanche
  SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 0, 200, 100));

  //Initialisation des positions des différentes surfaces et textes
  positiontexte1.x = (ecran->w - texte1->w) / 2;
  positiontexte1.y = 0;
  positiontexte2.x = (ecran->w - texte2->w) / 2;
  positiontexte2.y = 250 + (ecran->h - texte2->h) / 2;
  positionpendu.x = (ecran->w / 2) - (pendu->w / 2);
  positionpendu.y = (ecran->h / 2) - (pendu->h / 2);

  //Remplissage de l'écran principal avec la couleur blanche
  SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 0, 200, 100));

  //Blit du texte de la page d'accueil
  SDL_BlitSurface(texte1, NULL, ecran, &positiontexte1);
  SDL_BlitSurface(texte2, NULL, ecran, &positiontexte2);

  //Blit de l'image du pendu
  SDL_BlitSurface(pendu, NULL, ecran, &positionpendu);

  //Mise à jour de l'écran
  SDL_Flip(ecran);

  /*Une boucle infine afin de maintenir l'affichage et quitter le programme quand l'utilisateur ferme la fenêtre*/
  while (continuer) {
    SDL_PollEvent(&event);
    switch(event.type) {
    case SDL_QUIT:
      continuer = 0;
      break;
    //En cas d'apuui sur un bouton
    case SDL_KEYDOWN :
      //S'il s'agit du bouton "Entrer", appeler la fonction joueur_Pendu
      if(event.key.keysym.sym == SDLK_RETURN) gagnant = jouer_Pendu(ecran,j1,j2);
      continuer = 0;
      break;
    default: break;
    }
  }

  //Libération de la mémoire occupée par les surfaces et les polices et arrêt de la SDL
  TTF_CloseFont(police1);
  TTF_CloseFont(police2);
  SDL_FreeSurface(pendu);
  SDL_FreeSurface(texte1);
  SDL_FreeSurface(texte2);
  Mix_FreeMusic(musique); //Libération de la musique

  return gagnant;
}
Exemplo n.º 23
0
void initButtons()
{
	Uint8 i, fontSize;
	TTF_Font *font;
	SDL_Rect dest;
	char price[10];

	fontSize = 10;
	font = TTF_OpenFont("fonts/font1.ttf",fontSize);
	if(font == NULL)
	{
		fprintf(stderr,"Font failed to load.\n");
	}
	
	dest.x = 0;
	dest.y = fontSize+5;

	// set up tool tip surfaces
	for(i=0;i<MAX_UNIT_TYPES;++i)
	{
		HUD.aUnits[i].tip.bbox = SDL_CreateRGBSurface(SDL_HWSURFACE, 70, 40, screen->format->BitsPerPixel, screen->format->Rmask, screen->format->Gmask, screen->format->Bmask, screen->format->Amask);
		SDL_FillRect(HUD.aUnits[i].tip.bbox,&HUD.aUnits[i].tip.bbox->clip_rect,SDL_MapRGB(HUD.aUnits[i].tip.bbox->format, 100,100,100));
		SDL_SetAlpha(HUD.aUnits[i].tip.bbox, SDL_SRCALPHA|SDL_RLEACCEL, alpha );
	}

	for(i=0;i<MAX_STRUCT_TYPES;++i)
	{
		HUD.aStructs[i].tip.bbox = SDL_CreateRGBSurface(SDL_HWSURFACE, 70, 40, screen->format->BitsPerPixel, screen->format->Rmask, screen->format->Gmask, screen->format->Bmask, screen->format->Amask);	
		SDL_FillRect(HUD.aStructs[i].tip.bbox,&HUD.aStructs[i].tip.bbox->clip_rect,SDL_MapRGB(HUD.aStructs[i].tip.bbox->format, 100,100,100));
		SDL_SetAlpha(HUD.aStructs[i].tip.bbox, SDL_SRCALPHA|SDL_RLEACCEL, alpha );
	}

	// Battle Lord
	HUD.aUnits[BATTLELORD].img = LoadSprite("icons/blord.png",36,47);
	HUD.aUnits[BATTLELORD].stats = &units[BATTLELORD];
	HUD.aUnits[BATTLELORD].draw = true;
	HUD.aUnits[BATTLELORD].x = HUD.infox+20;			
	HUD.aUnits[BATTLELORD].y = HUD.infoy+108;
	HUD.aUnits[BATTLELORD].action = enqueueUnit;
	HUD.aUnits[BATTLELORD].tip.fColor.r = 255;
	HUD.aUnits[BATTLELORD].tip.fColor.g = 255;
	HUD.aUnits[BATTLELORD].tip.fColor.b = 255;
	SDL_BlitSurface(TTF_RenderText_Blended(font, "Battle Lord", HUD.aUnits[BATTLELORD].tip.fColor), NULL, HUD.aUnits[BATTLELORD].tip.bbox, NULL);
	sprintf(price, "$%i", units[BATTLELORD].price);
	SDL_BlitSurface(TTF_RenderText_Blended(font, price, HUD.aUnits[BATTLELORD].tip.fColor), NULL, HUD.aUnits[BATTLELORD].tip.bbox, &dest);

	// Spider Demon
	HUD.aUnits[SPIDERDEMON].img = LoadSprite("icons/spider.png",48,27);
	HUD.aUnits[SPIDERDEMON].stats = &units[SPIDERDEMON];
	HUD.aUnits[SPIDERDEMON].draw = true;
	HUD.aUnits[SPIDERDEMON].x = HUD.infox+83;
	HUD.aUnits[SPIDERDEMON].y = HUD.infoy+108;
	HUD.aUnits[SPIDERDEMON].action = enqueueUnit;
	HUD.aUnits[SPIDERDEMON].tip.fColor.r = 255;
	HUD.aUnits[SPIDERDEMON].tip.fColor.g = 255;
	HUD.aUnits[SPIDERDEMON].tip.fColor.b = 255;
	SDL_BlitSurface(TTF_RenderText_Blended(font, "Spider Demon", HUD.aUnits[SPIDERDEMON].tip.fColor), NULL, HUD.aUnits[SPIDERDEMON].tip.bbox, NULL);
	sprintf(price, "$%i", units[SPIDERDEMON].price);
	SDL_BlitSurface(TTF_RenderText_Blended(font, price, HUD.aUnits[SPIDERDEMON].tip.fColor), NULL, HUD.aUnits[SPIDERDEMON].tip.bbox, &dest);

	// Factory
	HUD.aStructs[BARRACKS].img = LoadSprite("icons/blord.png",36,47);
	HUD.aStructs[BARRACKS].stats = &structs[BARRACKS];
	HUD.aStructs[BARRACKS].draw = true;
	HUD.aStructs[BARRACKS].x = HUD.infox+20;
	HUD.aStructs[BARRACKS].y = HUD.infoy+40;
	HUD.aStructs[BARRACKS].action = placeStruct;
	HUD.aStructs[BARRACKS].tip.fColor.r = 255;
	HUD.aStructs[BARRACKS].tip.fColor.g = 255;
	HUD.aStructs[BARRACKS].tip.fColor.b = 255;
	SDL_BlitSurface(TTF_RenderText_Blended(font, "Barracks", HUD.aStructs[BARRACKS].tip.fColor), NULL, HUD.aStructs[BARRACKS].tip.bbox, NULL);
	sprintf(price, "$%i", structs[BARRACKS].price);
	SDL_BlitSurface(TTF_RenderText_Blended(font, price, HUD.aStructs[BARRACKS].tip.fColor), NULL, HUD.aStructs[BARRACKS].tip.bbox, &dest);

	// Factory 2
	HUD.aStructs[FACTORY].img = LoadSprite("icons/blord.png",39,50);
	HUD.aStructs[FACTORY].stats = &structs[FACTORY];
	HUD.aStructs[FACTORY].draw = true;
	HUD.aStructs[FACTORY].x = HUD.infox+83;
	HUD.aStructs[FACTORY].y = HUD.infoy+40;
	HUD.aStructs[FACTORY].action = placeStruct;
	HUD.aStructs[FACTORY].tip.fColor.r = 255;
	HUD.aStructs[FACTORY].tip.fColor.g = 255;
	HUD.aStructs[FACTORY].tip.fColor.b = 255;
	SDL_BlitSurface(TTF_RenderText_Blended(font, "Factory", HUD.aStructs[FACTORY].tip.fColor), NULL, HUD.aStructs[FACTORY].tip.bbox, NULL);
	sprintf(price, "$%i", structs[FACTORY].price);
	SDL_BlitSurface(TTF_RenderText_Blended(font, price, HUD.aStructs[FACTORY].tip.fColor), NULL, HUD.aStructs[FACTORY].tip.bbox, &dest);

	// Media player
	// Previous
	HUD.pButtons[0].x = HUD.playerx + 12;
	HUD.pButtons[0].y = HUD.playery + 5;
	HUD.pButtons[0].w = 13;
	HUD.pButtons[0].h = 7;
	HUD.pButtons[0].draw = true;
	HUD.pButtons[0].action = prev;

	// Play/pause
	HUD.pButtons[1].x = HUD.playerx + 30;
	HUD.pButtons[1].y = HUD.playery + 3;
	HUD.pButtons[1].w = 8;
	HUD.pButtons[1].h = 10;
	HUD.pButtons[1].draw = true;
	HUD.pButtons[1].action = play;

	// Stop
	HUD.pButtons[2].x = HUD.playerx + 42;
	HUD.pButtons[2].y = HUD.playery + 4;
	HUD.pButtons[2].w = 8;
	HUD.pButtons[2].h = 7;
	HUD.pButtons[2].draw = true;
	HUD.pButtons[2].action = stop;

	// Next
	HUD.pButtons[3].x = HUD.playerx + 56;
	HUD.pButtons[3].y = HUD.playery + 5;
	HUD.pButtons[3].w = 13;
	HUD.pButtons[3].h = 7;
	HUD.pButtons[3].draw = true;
	HUD.pButtons[3].action = next;
}
Exemplo n.º 24
0
//Fonction principale du jeu du Pendu, elle gérera l'affichage des différentes étapes d'une partie
int jouer_Pendu(SDL_Surface *ecran, char j1[], char j2[]) {
  //Déclaration des variables locales nécassaires pour la fonction
  SDL_Surface *s_mot_cache = NULL, *s_mot_decouvert = NULL, *resultat = NULL, *joueur = NULL;
  SDL_Rect position_mot_decouvert={200,500,0,0}, positionresultat = {50,400,0,0}, positionjoueur = {0,350,0,0};
  SDL_Event event;
  TTF_Font *police = NULL, *police2 = NULL;
  SDL_Color couleurNoire = {0, 0, 0, 0};
  int j=0, i, continuer=1, coups_reussis=0, coups_rates=1, joueuractuel = 1, joueur1, joueur2;
  char c, ch[30], mot_cache[30], mot_decouvert[30];
  Mix_Chunk *son1, *son2; 
  son1 = Mix_LoadWAV("../Music/Mini-jeux/coup_reussi_pendu.ogg");
  son2 = Mix_LoadWAV("../Music/Mini-jeux/coup_rate_pendu.ogg");

  srand(time(NULL));

  //Chargement de la police
  police = TTF_OpenFont("../Police/comicbd.ttf", 30);
  police2 = TTF_OpenFont("../Police/comicbd.ttf", 40);
  SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 255, 255, 255));
  joueur1 = joueur2 = 0;

  //Point de départ d'un tour (On retourne à cette ligne pour alterner les tours entre les joueurs)
 debut:
  /*Initialisation des variables utilisées durant une partie*/
  c = '0';
  //Génération d'un nombre au hasard entre 1 et 100, ce nombre sera l'indice du mot caché qui sera chargé du fichier mots.txt avec la fonction chargement_Mot
  i = rand()%100+1;
  chargement_Mot(mot_cache,i);
  //Initialisation de la chaine qui va contenir le mot saisi par un joueur
  initialiser(mot_cache,mot_decouvert);
  s_mot_decouvert = TTF_RenderText_Blended(police, mot_decouvert, couleurNoire);
  j++;
  continuer = 1;
  //Alternance du tour
  if(joueuractuel == 1) sprintf(ch,"Joueur : %s",j1);
  else sprintf(ch,"Joueur : %s",j2);
  joueur = TTF_RenderText_Blended(police2, ch, couleurNoire);
  //Boucle while qui gérera l'affichage des différentes étapes du jeu
  while(continuer) {
    SDL_WaitEvent(&event);
    switch(event.type) {
      //En cas de fermeture de la fenêtre
      case SDL_QUIT: continuer = 0; return 0; break;
	//En cas d'appuie sur un bouton, stocker le caractère dans la variable c
      case SDL_KEYDOWN : 
        switch(event.key.keysym.sym) {
          default : c = event.key.keysym.sym; break;
	}

	//Si c'est une lettre en majuscule, la convertir en minuscule
	if(c >= 'A' && c <= 'Z') c -= 32;
	//Si c'est une lettre, faire les tests nécessaires pour voir si le mot caché contient la lettre saisie
	if(c >= 'a' && c <= 'z') {
	  //Si la lettre saisie existe dans le mot caché, l'afficher dans sa/ses position(s) dans le mot découvert (le mot qui contient n tirets | n c'est la longueur du mot caché)
	  if (existe(mot_cache,c) > existe(mot_decouvert,c)) {
	    coups_reussis++;
	    Mix_PlayChannel(1,son1,0);
	    for (i = 0; mot_cache[i] != '\0'; i++) {
	      if (mot_cache[i] == c)
		mot_decouvert[i] = c;
	    }
	    s_mot_decouvert = TTF_RenderText_Blended(police, mot_decouvert, couleurNoire);  
	  }
    /*Si la lettre n'existe pas dans mot_cache, on incrémente les coups ratés de 1, puis on appelle la fonction bonhomme 
      avec le nombre coups_rates qui s'occupera d'afficher l'image correspondante du pendu*/ 
	  else if(existe(mot_cache,c) == existe(mot_decouvert,c)){
	    Mix_PlayChannel(1,son2,0);
	    coups_rates++;
	  } 
	}
	break;
	default : break;
    }

    SDL_FillRect(ecran, NULL, SDL_MapRGB(ecran->format, 255, 255, 255));
    bonhomme(ecran,coups_rates);
    SDL_BlitSurface(s_mot_decouvert,NULL, ecran, &position_mot_decouvert);
    //Si le joueur atteint le nombre max de coups ratés, on affiche le mot caché et on garde le nombre de coups ratés afin de le comparer avec celui de l'autre joueur.
    if(coups_rates == 10) {
      if(joueuractuel == 1) {joueuractuel = 2; joueur1 = coups_rates;}
      else {joueuractuel = 1; joueur2 = coups_rates;}
      continuer = 0;
      coups_rates = 1;
      sprintf(ch,"Le mot etait '%s'",mot_cache);
      resultat = TTF_RenderText_Blended(police2, ch, couleurNoire);
      SDL_BlitSurface(resultat,NULL, ecran, &positionresultat);
    }
    //Si le joueur trouve le mot caché, on affiche le texte correspondant et on garde le nombre de coups ratés afin de le comparer avec celui de l'autre joueur.
    else if(!strcmp(mot_cache,mot_decouvert)) {
      if(joueuractuel == 1) {joueuractuel = 2; joueur1 = coups_rates;}
      else {joueuractuel = 1; joueur2 = coups_rates;}
      sprintf(ch,"Bravoo !");
      resultat = TTF_RenderText_Blended(police2, ch, couleurNoire);
      SDL_BlitSurface(resultat,NULL, ecran, &positionresultat);
      continuer = 0;
      coups_rates = 1;
    }
    SDL_BlitSurface(joueur,NULL, ecran, &positionjoueur);
    SDL_Flip(ecran);
  }
  sleep(2);

  //Si les 2 joueurs ont le même score ou si c'est le tour du 2ème joueur, relancer le jeu avec un mot différent.
  if(joueur1 == joueur2 || j&1) goto debut;

  SDL_FreeSurface(s_mot_decouvert);
  SDL_FreeSurface(s_mot_cache);
  SDL_FreeSurface(resultat);
  Mix_FreeChunk(son1);//Libération du son
  Mix_FreeChunk(son2);//Libération du son

  //Renvoie de l'indice du gagnant
  if(joueur1 > joueur2) return 2;
  else return 1;
}
Exemplo n.º 25
0
// Draws the interface to the screen
void drawInterface()
{
	Sprite *temp;
	int i = -1;
	int x, y;
	TTF_Font *font;
	SDL_Surface *button;
	SDL_Rect dest;
	SDL_Surface icon;

	// fade HUD in/out
	if(HUD.menu != 0 && aSlide == false)
	{
		if(alpha > 4)
			alpha -= 5;
		else
			alpha = SDL_ALPHA_TRANSPARENT;
	}
	else if(alpha < (255*aLevel))
		alpha += 5;
	else
	{
		alpha = 255*aLevel;
	}

	if(HUD.menu > 0)
		SDL_FillRect(screen,&screen->clip_rect,SDL_MapRGB(screen->format, 0,0,0));
	else
	{
		if(players[0].placing > -1)
			placeStruct2();
	}

	// load font for text
	font = TTF_OpenFont("fonts/font1.ttf",30);
	if(font == NULL)
	{
		fprintf(stderr,"Font failed to load.\n");
	}

	// unless alpha > 0, don't bother drawing the interface
	if(alpha > 0)
	{
		// minimap
		temp = LoadSprite("hud/minimap.png",HUD.mapw,HUD.maph);
		SDL_SetAlpha( temp->image, SDL_SRCALPHA|SDL_RLEACCEL, alpha );
		DrawSprite(temp,screen,HUD.mapx,HUD.mapy,0);

		// info bar
		temp = LoadSprite("hud/infobar.png",HUD.infow,HUD.infoh);
		SDL_SetAlpha( temp->image, SDL_SRCALPHA|SDL_RLEACCEL, alpha );
		DrawSprite(temp,screen,HUD.infox,HUD.infoy,0);

		// Draw structure icons
		while(++i<MAX_STRUCT_TYPES)
		{
			if( HUD.aStructs[i].draw == false ) continue;

			// Draw background
			temp = LoadSprite("hud/qbutton.png",58,58);
			SDL_SetAlpha( temp->image, SDL_SRCALPHA|SDL_RLEACCEL, alpha );
			DrawSprite(temp, screen, HUD.aStructs[i].x, HUD.aStructs[i].y, 0);

			// Draw structure icon
			SDL_SetColorKey(HUD.aStructs[i].img->image, SDL_SRCCOLORKEY , SDL_MapRGB(HUD.aStructs[i].img->image->format, 255,255,255));
			SDL_SetAlpha(HUD.aStructs[i].img->image, SDL_SRCALPHA|SDL_RLEACCEL, alpha );
			DrawSprite(HUD.aStructs[i].img, screen, HUD.aStructs[i].x+((58-HUD.aStructs[i].img->w)*.5), HUD.aStructs[i].y+((58-HUD.aStructs[i].img->h)*.5), 0);
		}

		// Draw unit icons
		i = -1;
		while(++i<MAX_UNIT_TYPES)
		{
			if( HUD.aUnits[i].draw == false ) continue;

			// Draw background
			temp = LoadSprite("hud/qbutton.png",58,58);
			SDL_SetAlpha(temp->image, SDL_SRCALPHA|SDL_RLEACCEL, alpha );
			DrawSprite(temp,screen,HUD.aUnits[i].x,HUD.aUnits[i].y,0);

			// Draw unit icon
			SDL_SetColorKey(HUD.aUnits[i].img->image, SDL_SRCCOLORKEY , SDL_MapRGB(HUD.aUnits[i].img->image->format, 255,255,255));
			SDL_SetAlpha(HUD.aUnits[i].img->image, SDL_SRCALPHA|SDL_RLEACCEL, alpha );
			DrawSprite(HUD.aUnits[i].img, screen, HUD.aUnits[i].x+((58-HUD.aUnits[i].img->w)*.5), HUD.aUnits[i].y+((58-HUD.aUnits[i].img->h)*.5), 0);
		}

		// media player bar
		temp = LoadSprite("hud/mplayerbar.png",HUD.playerw,HUD.playerh);
		SDL_SetAlpha( temp->image, SDL_SRCALPHA|SDL_RLEACCEL, alpha );
		DrawSprite(temp,screen,HUD.playerx,HUD.playery,0);
		updatePlayer();

		// tool tips
		if(HUD.ttips)
			showTip();
	}

	// Draw menu
	if( (HUD.menu > 0) && (HUD.menu != 5) )
	{
		temp = LoadSprite("hud/menu.png",640,480);

		// center and draw the menu panel and buttons
		if(screen->w > 640)
			x = screen->w * .5 - 320;
		else
			x = 0;
		if(screen->h > 480)
			y = screen->h * .5 - 240;
		else
			y = 0;

		DrawSprite(temp,screen,x,y,0);
	}

	// Draw the button text
	// Main menu
	if(HUD.menu == 1)
	{
		// New Game
		dest.x = MENU_X+250;
		dest.y = MENU_Y+55;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 1)
			button = TTF_RenderText_Blended(font,"New Game",oColor);
		else
			button = TTF_RenderText_Blended(font,"New Game",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Resume
		dest.x = MENU_X+260;
		dest.y = MENU_Y+138;
		dest.w = 100;
		dest.h = 50;

		if(players[0].inGame)
		{
			if(mouseOver == 2)
				button = TTF_RenderText_Blended(font,"Resume",oColor);
			else
				button = TTF_RenderText_Blended(font,"Resume",color);
		}
		else
			button = TTF_RenderText_Blended(font,"Resume",bColor);

		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Save/Load
		dest.x = MENU_X+245;
		dest.y = MENU_Y+223;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 3)
			button = TTF_RenderText_Blended(font,"Save/Load",oColor);
		else
			button = TTF_RenderText_Blended(font,"Save/Load",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Options
		dest.x = MENU_X+260;
		dest.y = MENU_Y+302;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 4)
			button = TTF_RenderText_Blended(font,"Options",oColor);
		else
			button = TTF_RenderText_Blended(font,"Options",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Quit
		dest.x = MENU_X+285;
		dest.y = MENU_Y+385;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 5)
			button = TTF_RenderText_Blended(font,"Quit",oColor);
		else
			button = TTF_RenderText_Blended(font,"Quit",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);
	}

	// Save/Load submenu
	else if(HUD.menu == 2)
	{
		// Save
		dest.x = MENU_X+275;
		dest.y = MENU_Y+55;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 1)
			button = TTF_RenderText_Blended(font,"Save",oColor);
		else
			button = TTF_RenderText_Blended(font,"Save",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Load
		dest.x = MENU_X+275;
		dest.y = MENU_Y+138;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 2)
			button = TTF_RenderText_Blended(font,"Load",oColor);
		else
			button = TTF_RenderText_Blended(font,"Load",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Main Menu
		dest.x = MENU_X+245;
		dest.y = MENU_Y+385;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 5)
			button = TTF_RenderText_Blended(font,"Main Menu",oColor);
		else
			button = TTF_RenderText_Blended(font,"Main Menu",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);
	}

	// Options submenu
	else if(HUD.menu == 3)
	{
		// Sound
		dest.x = MENU_X+275;
		dest.y = MENU_Y+55;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 1)
			button = TTF_RenderText_Blended(font,"Sound",oColor);
		else
			button = TTF_RenderText_Blended(font,"Sound",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Controls
		dest.x = MENU_X+260;
		dest.y = MENU_Y+138;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 2)
			button = TTF_RenderText_Blended(font,"Controls",oColor);
		else
			button = TTF_RenderText_Blended(font,"Controls",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// HUD
		dest.x = MENU_X+285;
		dest.y = MENU_Y+223;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 3)
			button = TTF_RenderText_Blended(font,"HUD",oColor);
		else
			button = TTF_RenderText_Blended(font,"HUD",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Game
		dest.x = MENU_X+270;
		dest.y = MENU_Y+302;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 4)
			button = TTF_RenderText_Blended(font,"Game",oColor);
		else
			button = TTF_RenderText_Blended(font,"Game",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Main Menu
		dest.x = MENU_X+245;
		dest.y = MENU_Y+385;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 5)
			button = TTF_RenderText_Blended(font,"Main Menu",oColor);
		else
			button = TTF_RenderText_Blended(font,"Main Menu",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);
	}

	// Sound submenu
	else if(HUD.menu == 4)
	{
		// Sound effects volume
		dest.x = MENU_X+140;
		dest.y = MENU_Y+55;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 1)
			button = TTF_RenderText_Blended(font,"Effects Volume",oColor);
		else
			button = TTF_RenderText_Blended(font,"Effects Volume",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Draw slots for volume sliders
		dest.x += 235;
		dest.y += 15;
		temp = LoadSprite("hud/menuslots.png",126,13);
		DrawSprite(temp,screen,dest.x,dest.y,0);

		dest.y += 85;
		temp = LoadSprite("hud/menuslots.png",126,13);
		DrawSprite(temp,screen,dest.x,dest.y,0);

		// Update info based on slider position
		dest.x += 10;
		dest.w = 100;
		if( (audio.slide == 1) )
		{
			if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON_LMASK)
			{
				audio.eVol = moveSlider(&audio.evSlider,&dest);
			}
			else
				audio.slide = 0;
		}

		else if( (audio.slide == 2) )
		{
			if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON_LMASK)
			{
				audio.mVol = moveSlider(&audio.mvSlider,&dest);
			}
			else
				audio.slide = 0;
		}
		else
		{
			audio.evSlider.x = dest.x + (dest.w*audio.eVol);
			audio.mvSlider.x = dest.x + (dest.w*audio.mVol);
		}

		// Draw sliders
		temp = LoadSprite("hud/slider.png",50,24);
		button = IMG_Load("hud/slider.png");
		SDL_SetColorKey(button, 0, 0);
		temp->image = SDL_DisplayFormatAlpha(button);
		SDL_FreeSurface(button);

		temp = LoadSprite("hud/slider.png",50,24);
		DrawSprite(temp,screen,audio.evSlider.x-(audio.evSlider.w*.5),audio.evSlider.y,0);

		temp = LoadSprite("hud/slider.png",50,24);
		DrawSprite(temp,screen,audio.mvSlider.x-(audio.mvSlider.w*.5),audio.mvSlider.y,0);

		// Music volume
		dest.x = MENU_X+140;
		dest.y = MENU_Y+138;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 2)
			button = TTF_RenderText_Blended(font,"Music Volume",oColor);
		else
			button = TTF_RenderText_Blended(font,"Music Volume",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Mute
		dest.x = MENU_X+275;
		dest.y = MENU_Y+223;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 3)
			button = TTF_RenderText_Blended(font,"Mute",oColor);
		else
			button = TTF_RenderText_Blended(font,"Mute",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Back
		dest.x = MENU_X+285;
		dest.y = MENU_Y+385;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 5)
			button = TTF_RenderText_Blended(font,"Back",oColor);
		else
			button = TTF_RenderText_Blended(font,"Back",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);
	}

	// HUD submenu
	else if(HUD.menu == 6)
	{
		// Alpha level
		dest.x = MENU_X+175;
		dest.y = MENU_Y+55;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 1)
			button = TTF_RenderText_Blended(font,"Alpha Level",oColor);
		else
			button = TTF_RenderText_Blended(font,"Alpha Level",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Draw slot for alpha slider
		dest.x += 200;
		dest.y += 15;
		temp = LoadSprite("hud/menuslots.png",126,13);
		DrawSprite(temp,screen,dest.x,dest.y,0);

		// Update info based on slider position
		dest.x += 10;
		dest.w = 100;
		if( (aSlide == true) )
		{
			if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON_LMASK)
			{
				aLevel = moveSlider(&aSlider,&dest);
			}
			else
				aSlide = false;
		}

		else
		{
			aSlider.x = dest.x + (dest.w*aLevel);
		}

		// Draw sliders
		temp = LoadSprite("hud/slider.png",50,24);
		DrawSprite(temp,screen,aSlider.x-(aSlider.w*.5),aSlider.y,0);

		// Save
		dest.x = MENU_X+285;
		dest.y = MENU_Y+138;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 2)
			button = TTF_RenderText_Blended(font,"Save",oColor);
		else
			button = TTF_RenderText_Blended(font,"Save",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Load
		dest.x = MENU_X+285;
		dest.y = MENU_Y+223;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 3)
			button = TTF_RenderText_Blended(font,"Load",oColor);
		else
			button = TTF_RenderText_Blended(font,"Load",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Back
		dest.x = MENU_X+285;
		dest.y = MENU_Y+385;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 5)
			button = TTF_RenderText_Blended(font,"Back",oColor);
		else
			button = TTF_RenderText_Blended(font,"Back",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);
	}

	// Game submenu
	else if(HUD.menu == 7)
	{
		// Scroll speed
		dest.x = MENU_X+175;
		dest.y = MENU_Y+55;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 1)
			button = TTF_RenderText_Blended(font,"Scroll Speed",oColor);
		else
			button = TTF_RenderText_Blended(font,"Scroll Speed",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);

		// Draw slot for scroll speed slider
		dest.x += 200;
		dest.y += 15;
		temp = LoadSprite("hud/menuslots.png",126,13);
		DrawSprite(temp,screen,dest.x,dest.y,0);

		dest.x += 10;
		dest.w = 100;

		if( (HUD.sSlide == true) )
		{
			if(SDL_GetMouseState(NULL,NULL)&SDL_BUTTON_LMASK)
			{
				sSpeed = moveSlider(&sSlider,&dest);
			}
			else
				HUD.sSlide = false;
		}

		else
		{
			sSlider.x = dest.x + (dest.w*sSpeed);
		}

		// Draw slider
		temp = LoadSprite("hud/slider.png",50,24);
		DrawSprite(temp,screen,sSlider.x-(sSlider.w*.5),sSlider.y,0);

		// Tool tips on/off
		dest.x = MENU_X+215;
		dest.y = MENU_Y+138;
		dest.w = 100;
		dest.h = 50;

		if(mouseOver == 2)
			button = TTF_RenderText_Blended(font,"Tool Tips",oColor);
		else
			button = TTF_RenderText_Blended(font,"Tool Tips",color);
		if(button != NULL)
		{
			SDL_BlitSurface(button,NULL,screen,&dest);
			SDL_FreeSurface(button);
		}

		dest.x += 150;
		if(HUD.ttips)
			button = TTF_RenderText_Blended(font,"On",color);
		else
			button = TTF_RenderText_Blended(font,"Off",color);
		if(button != NULL)
		{
			SDL_BlitSurface(button,NULL,screen,&dest);
			SDL_FreeSurface(button);
		}

		// Back
		dest.x = MENU_X+285;
		dest.y = MENU_Y+385;
		dest.w = 100;
		dest.h = 50;
		if(mouseOver == 5)
			button = TTF_RenderText_Blended(font,"Back",oColor);
		else
			button = TTF_RenderText_Blended(font,"Back",color);
		if(button != NULL)
			SDL_BlitSurface(button,NULL,screen,&dest);
		SDL_FreeSurface(button);
	}

	if(font != NULL)
		TTF_CloseFont(font);
}
Exemplo n.º 26
0
void Graphics::clear(){
	// SDL_fillrect( this is our surface that we want to fill 
					//next parameter is the destination rectangle that we want to fill, we pul NULL here because we want it to fill the whole screen
	// next is the color (Uint32) but we will just put 0 for now as we just want it black
	SDL_FillRect(screen_ ,  NULL , 0);
}
Exemplo n.º 27
0
void View::clearSurface(SDL_Surface* surf)
{
	SDL_FillRect(surf, NULL, 0x000000);
}
Exemplo n.º 28
0
void Board::DrawBlock(SDL_Rect *rect, Uint8 r, Uint8 g, Uint8 b)
{
	SDL_FillRect(board_surface, rect, SDL_MapRGB(board_surface->format, r, g, b));
}
Exemplo n.º 29
0
int your_test(int argc, char **argv)
{
    int done=0;

    /* check args */
    if(argc!=2)
    {
        fprintf(stderr,"%s file.ttf\n",argv[0]);
        return 1;
    }

    /* initialize the cache to NULL */
    memset(text,0,sizeof(text));

    /* start SDL video */
    if(SDL_Init(SDL_INIT_VIDEO)==-1)
    {
        printf("SDL_Init: %s\n",SDL_GetError());
        return 1;
    }
    atexit(SDL_Quit); /* remember to quit SDL */

    /* open the screen */
    if(!(screen=SDL_SetVideoMode(1200,1000,0,0)))
    {
        printf("SDL_SetVideoMode: %s\n",SDL_GetError());
        return 1;
    }

    /* allow for key repeat (so the user can hold down a key...) */
    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);

    /* start SDL_ttf */
    if(TTF_Init()==-1)
    {
        printf("TTF_Init: %s\n", TTF_GetError());
        return 2;
    }
    atexit(TTF_Quit); /* remember to quit SDL_ttf */
    atexit(free_font); /* remember to free any loaded font and glyph cache */

    while(!done)
    {
        SDL_Event event;
        static int x=0, y=0, need_draw=1,last_size=0, last_start_glyph=-1;

        /* smartly load font and generate new glyph cache (font_size change) */
        if(last_size!=font_size)
        {
            if(font_size<1)
                font_size=1;
            load_font(argv[1], font_size);
            need_draw=1;
            last_size=font_size;
        }
        /* smartly generate new glyph cache (page change) */
        if(last_start_glyph!=start_glyph)
        {
            cache_glyphs();
            need_draw=1;
            last_start_glyph=start_glyph;
        }
        /* smartly redraw as needed */
        if(need_draw)
        {
            SDL_FillRect(screen,0,~0);
            draw_table(x,y);
            SDL_Flip(screen);
            need_draw=0;
        }
        /* wait for events and handle them */
        /* this waits for one, then handles all that are queued before finishing */
        if(SDL_WaitEvent(&event))
            do {
                switch(event.type)
                {
                case SDL_QUIT:
                    done=1;
                    break;
                case SDL_KEYDOWN:
                    switch(event.key.keysym.sym)
                    {
                    case '0':
                        start_glyph=0;
                        break;
                    case SDLK_LEFT:
                        start_glyph=(start_glyph+0x10000-0x80)&0xffff;
                        break;
                    case SDLK_RIGHT:
                        start_glyph=(start_glyph+0x80)&0xffff;
                        break;
                    case SDLK_UP:
                        font_size++;
                        break;
                    case SDLK_DOWN:
                        font_size--;
                        break;
                    case 'n':
                        style=TTF_STYLE_NORMAL;
                        last_start_glyph=-1;
                        break;
                    case 'b':
                        style^=TTF_STYLE_BOLD;
                        last_start_glyph=-1;
                        break;
                    case 'i':
                        style^=TTF_STYLE_ITALIC;
                        last_start_glyph=-1;
                        break;
                    case 'u':
                        style^=TTF_STYLE_UNDERLINE;
                        last_start_glyph=-1;
                        break;
                    case 's':
                        style^=TTF_STYLE_STRIKETHROUGH;
                        last_start_glyph=-1;
                        break;
                    case 'k':
                        kerning=!kerning;
                        printf("kerning=%d\n",kerning);
                        last_start_glyph=-1;
                        break;
                    case 'h':
                        hinting=(hinting+1)%4;
                        printf("hinting=%s\n",
                            hinting==0?"Normal":
                        hinting==1?"Light":
                        hinting==2?"Mono":
                        hinting==3?"None":
                        "Unknonwn");
                        last_start_glyph=-1;
                        break;
                    case '=':
                        ++outline;
                        printf("outline=%d\n",outline);
                        last_start_glyph=-1;
                        break;
                    case '-':
                        if(outline>0)
                            --outline;
                        printf("outline=%d\n",outline);
                        last_start_glyph=-1;
                        break;
                    case 'q':
                    case SDLK_ESCAPE:
                        done=1;
                        break;
                    default:
                        break;
                    }
                    break;
                case SDL_MOUSEMOTION:
                    if(event.motion.state)
                    {
                        x=event.motion.x;
                        y=event.motion.y;
                        need_draw=1;
                    }
                    break;
                case SDL_MOUSEBUTTONDOWN:
                    x=event.button.x;
                    y=event.button.y;
                    need_draw=1;
                    break;
                }
            } while(SDL_PollEvent(&event));
    } /* main loop */

    return 0;
}
Exemplo n.º 30
0
int
main (int argc, char *argv[])
{
  /* Process command line arguments */
  if (argc != 2)
    {
      fprintf (stderr, "Usage: %s <image path>\n", argv[0]);
      return (EXIT_FAILURE);
    }
  char *image_path = argv[1];

  /* Initialize subsystems */
  atexit (quit);
  if (SDL_Init (SDL_INIT_VIDEO))
    {
      fprintf (stderr, "Could not initialize SDL: %s\n", SDL_GetError ());
      return (EXIT_FAILURE);
    }
  char title[FILENAME_MAX];
  sprintf (title, "seamless - %s", image_path);
  SDL_WM_SetCaption (title, title);
  if (IMG_Init (0))
    {
      fprintf (stderr, "Could not initialize SDL_image: %s\n",
	       IMG_GetError ());
      return (EXIT_FAILURE);
    }

  /* Prepare drawing */
  SDL_Surface *image = IMG_Load (image_path);
  if (!image)
    {
      fprintf (stderr, "Could not load image %s: %s\n", image_path,
	       IMG_GetError ());
      return (EXIT_FAILURE);
    }
  SDL_Surface *screen =
    SDL_SetVideoMode (image->w, image->h, image->format->BitsPerPixel,
		      SDL_SWSURFACE);
  if (!screen)
    {
      fprintf (stderr, "Could not set video mode: %s\n", SDL_GetError ());
      return (EXIT_FAILURE);
    }


  /* Main loop */
  bool running = true;
  Uint32 black = SDL_MapRGB (screen->format, 0, 0, 0);
  SDL_Event event;
  float *array;
  char *pred;
  SDL_Surface *original;

  while (running)
    {
      while (SDL_PollEvent (&event))
	{
	  switch (event.type)
	    {
	    case SDL_QUIT:
	      running = false;
	      break;
            case SDL_KEYDOWN:
              switch (event.key.keysym.sym)
                {
                  case SDLK_q:
                  case SDLK_ESCAPE:
                    running = 0;
                    break;
                  case SDLK_RETURN:
                    for (int i = 0; i < 50; ++i)
                      {
                        array = energize (image, steepest_neighbor);
                        pred = dynamic_program (array, image->w, image->h);

                        original = image;
                        image = remove_seam (original,
                          min_pixel (array, original->w, original->h), pred);

                        SDL_FreeSurface (original);
                        free (array);
                        free (pred);
                      }
                    break;
                  default:
                    break;
                }
            }
	}

      SDL_FillRect (screen, NULL, black);

      SDL_BlitSurface (image, NULL, screen, NULL);

      SDL_Flip (screen);
    }

  return (EXIT_SUCCESS);
}