int main(int argc, char *argv[])
{
	char *argv0 = argv[0];
	SDL_Surface *screen;
	TTF_Font *font;
	SDL_Surface *text, *temp;
	int ptsize;
	int i, done;
	int rdiff, gdiff, bdiff;
	SDL_Color colors[NUM_COLORS];
	SDL_Color white = { 0xFF, 0xFF, 0xFF, 0 };
	SDL_Color black = { 0x00, 0x00, 0x00, 0 };
	SDL_Color *forecol;
	SDL_Color *backcol;
	SDL_Rect dstrect;
	SDL_Event event;
	int rendersolid;
	int renderstyle;
	int outline;
	int hinting;
	int kerning;
	int dump;
	enum {
		RENDER_LATIN1,
		RENDER_UTF8,
		RENDER_UNICODE
	} rendertype;
	char *message, string[128];

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

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

	/* Initialize SDL */
	if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) {
		fprintf(stderr, "Couldn't initialize SDL: %s\n",SDL_GetError());
		return(2);
	}

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

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

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

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

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

		}
		cleanup(0);
	}

	/* Set a 640x480x8 video mode */
	screen = SDL_SetVideoMode(640, 480, 8, SDL_SWSURFACE);
	if ( screen == NULL ) {
		fprintf(stderr, "Couldn't set 640x480x8 video mode: %s\n",
							SDL_GetError());
		cleanup(2);
	}

	/* Set a palette that is good for the foreground colored text */
	rdiff = backcol->r - forecol->r;
	gdiff = backcol->g - forecol->g;
	bdiff = backcol->b - forecol->b;
	for ( i=0; i<NUM_COLORS; ++i ) {
		colors[i].r = forecol->r + (i*rdiff)/4;
		colors[i].g = forecol->g + (i*gdiff)/4;
		colors[i].b = forecol->b + (i*bdiff)/4;
	}
	SDL_SetColors(screen, colors, 0, NUM_COLORS);

	/* Clear the background to background color */
	SDL_FillRect(screen, NULL,
			SDL_MapRGB(screen->format, backcol->r, backcol->g, backcol->b));
	SDL_UpdateRect(screen, 0, 0, 0, 0);

	/* Show which font file we're looking at */
	sprintf(string, "Font file: %s", argv[0]);  /* possible overflow */
	if ( rendersolid ) {
		text = TTF_RenderText_Solid(font, string, *forecol);
	} else {
		text = TTF_RenderText_Shaded(font, string, *forecol, *backcol);
	}
	if ( text != NULL ) {
		dstrect.x = 4;
		dstrect.y = 4;
		dstrect.w = text->w;
		dstrect.h = text->h;
		SDL_BlitSurface(text, NULL, screen, &dstrect);
		SDL_FreeSurface(text);
	}
	
	/* Render and center the message */
	if ( argc > 2 ) {
		message = argv[2];
	} else {
		message = DEFAULT_TEXT;
	}
	switch (rendertype) {
	    case RENDER_LATIN1:
		if ( rendersolid ) {
			text = TTF_RenderText_Solid(font,message,*forecol);
		} else {
			text = TTF_RenderText_Shaded(font,message,*forecol,*backcol);
		}
		break;

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

	    case RENDER_UNICODE:
		{
			Uint16 unicode_text[BUFSIZ];
			int index;
#ifdef HAVE_ICONV
			/* Use iconv to convert the message into utf-16.
			 * "char" and "" are aliases for the local 8-bit encoding */
			iconv_t cd;
			/*ICONV_CONST*/ char *from_str = message;
			char *to_str = (char*)unicode_text;
			size_t from_sz = strlen(message) + 1;
			size_t to_sz = sizeof(unicode_text);
			size_t res;
			int i;

			if ((cd = iconv_open("UTF-16", "char")) == (iconv_t)-1
			    && (cd = iconv_open("UTF-16", "")) == (iconv_t)-1) {
				perror("Couldn't open iconv");
				exit(1);
			}

			res = iconv(cd, &from_str, &from_sz, &to_str, &to_sz);
			if (res == -1) {
				perror("Couldn't use iconv");
				exit(1);
			}

			iconv_close(cd);
#else
			/* Convert the message from ascii into utf-16.
			 * This is unreliable as a test because it always
			 * gives the local ordering. */
			for (index = 0; message[index]; index++) {
				unicode_text[index] = message[index];
			}
			unicode_text[index] = 0;
#endif

			if ( rendersolid ) {
				text = TTF_RenderUNICODE_Solid(font,
					unicode_text, *forecol);
			} else {
				text = TTF_RenderUNICODE_Shaded(font,
					unicode_text, *forecol, *backcol);
			}
		}
		break;
	    default:
		text = NULL; /* This shouldn't happen */
		break;
	}
	if ( text == NULL ) {
		fprintf(stderr, "Couldn't render text: %s\n", SDL_GetError());
		TTF_CloseFont(font);
		cleanup(2);
	}
	dstrect.x = (screen->w - text->w)/2;
	dstrect.y = (screen->h - text->h)/2;
	dstrect.w = text->w;
	dstrect.h = text->h;
	printf("Font is generally %d big, and string is %hd big\n",
						TTF_FontHeight(font), text->h);

	/* Blit the text surface */
	if ( SDL_BlitSurface(text, NULL, screen, &dstrect) < 0 ) {
		fprintf(stderr, "Couldn't blit text to display: %s\n", 
								SDL_GetError());
		TTF_CloseFont(font);
		cleanup(2);
	}
	SDL_UpdateRect(screen, 0, 0, 0, 0);

	/* Set the text colorkey and convert to display format */
	if ( SDL_SetColorKey(text, SDL_SRCCOLORKEY|SDL_RLEACCEL, 0) < 0 ) {
		fprintf(stderr, "Warning: Couldn't set text colorkey: %s\n",
								SDL_GetError());
	}
	temp = SDL_DisplayFormat(text);
	if ( temp != NULL ) {
		SDL_FreeSurface(text);
		text = temp;
	}

	/* Wait for a keystroke, and blit text on mouse press */
	done = 0;
	while ( ! done ) {
		if ( SDL_WaitEvent(&event) < 0 ) {
			fprintf(stderr, "SDL_PullEvent() error: %s\n",
								SDL_GetError());
			done = 1;
			continue;
		}
		switch (event.type) {
			case SDL_MOUSEBUTTONDOWN:
				dstrect.x = event.button.x - text->w/2;
				dstrect.y = event.button.y - text->h/2;
				dstrect.w = text->w;
				dstrect.h = text->h;
				if ( SDL_BlitSurface(text, NULL, screen,
							&dstrect) == 0 ) {
					SDL_UpdateRects(screen, 1, &dstrect);
				} else {
					fprintf(stderr,
					"Couldn't blit text to display: %s\n", 
								SDL_GetError());
				}
				break;
				
			case SDL_KEYDOWN:
			case SDL_QUIT:
				done = 1;
				break;
			default:
				break;
		}
	}
	SDL_FreeSurface(text);
	TTF_CloseFont(font);
	cleanup(0);

	/* Not reached, but fixes compiler warnings */
	return 0;
}
Beispiel #2
0
int
main (int argc, char ** argv)
{
  int numloops = 0;
  int fpstimer;
  double a1, a2;
  tolerance_file_t * tol = get_tolerance ("colors.tol");
  memset (tol, '\0', sizeof (tolerance_file_t));
  int do_blob = -1;
  int do_text = -1;
  Uint8 mouse_button;
  SDL_Surface * image;
  SDL_Surface * image_2;
  SDL_Surface * screen;
  SDL_Surface * back = IMG_Load ("back.png");
  SDL_Color white = {255, 255, 255};
  SDL_Event event;
  char * jpeg_buff;
  char * jpeg_buff_2;
  int jpeg_buff_size;
  int jpeg_buff_size_2;
  int x, y;
  FILE * log_fp;
  blob * cam1_green;
  blob * cam1_red;
  blob * cam2_green;
  blob * cam2_red;
  blob * vision_targets = NULL;
  CvCapture * capture;
  CvCapture * capture_2;
  IplImage * cam_img;
  IplImage * cam_img_2;
  FILE * color_fp;
  if (SDL_Init (SDL_INIT_VIDEO | SDL_INIT_TIMER) == -1) {
    SDL_Quit ();
    printf ("SDL Initialization failed\n");
    exit (1);
  }
  if ((screen = SDL_SetVideoMode (800, 600, 32, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_FULLSCREEN )) == NULL) {
    SDL_Quit ();
    printf ("Could not create output surface\n");
    exit (1);
  }
  if (TTF_Init () == -1) {
    SDL_Quit ();
    printf ("TTF_Init: %s\n", TTF_GetError());
    exit (1);
  }
  if (!(capture = cvCaptureFromCAM (0))) {
    SDL_Quit ();
    printf ("Failed to start capture\n");
    exit (1);
  }
  if (!(capture_2 = cvCaptureFromCAM (1))) {
    SDL_Quit ();
    printf ("Failed to start capture\n");
    exit (1);
  }
  int start = SDL_GetTicks ();
  int lastfps;
  TTF_Font * arial = TTF_OpenFont ("arial.ttf", 12);
  while (1) {
    fpstimer = SDL_GetTicks ();
    numloops++;
    if (fpstimer - start > 1000) {
      start = SDL_GetTicks ();
      lastfps = numloops;
      numloops = 0;
    }
    while (SDL_PollEvent (&event)) {
      switch (event.type) {
        case SDL_KEYDOWN:
          switch (event.key.keysym.sym) {
            case 'q':
              TTF_Quit ();
              SDL_Quit ();
              exit (0);
            break;
            case 'b':
              do_blob = -do_blob;
            break;
            case 'v':
              do_text = -do_text;
            break;
            case 'i':
              tol->cam1_green.blob_minlength++;
            break;
            case 'k':
              tol->cam1_green.blob_minlength--;
            break;
            case 'o':
              tol->cam1_green.blob_tolerance++;
            break;
            case 'l':
              tol->cam1_green.blob_tolerance--;
            break;
            case 'y':
              tol->cam1_red.blob_minlength++;
            break;
            case 'h':
              tol->cam1_red.blob_minlength--;
            break;
            case 'u':
              tol->cam1_red.blob_tolerance++;
            break;
            case 'j':
              tol->cam1_red.blob_tolerance--;
            break;
            case 'w':
              tol->cam2_green.blob_minlength++;
            break;
            case 's':
              tol->cam2_green.blob_minlength--;
            break;
            case 'e':
              tol->cam2_green.blob_tolerance++;
            break;
            case 'd':
              tol->cam2_green.blob_tolerance--;
            break;
            case 'r':
              tol->cam2_red.blob_minlength++;
            break;
            case 'f':
              tol->cam2_red.blob_minlength--;
            break;
            case 't':
              tol->cam2_red.blob_tolerance++;
            break;
            case 'g':
              tol->cam2_red.blob_tolerance--;
            break;
            case 'z':
              color_fp = fopen ("colors.tol", "wb");
              fwrite (tol, sizeof (tolerance_file_t), 1, color_fp);
              fclose (color_fp);
            break;
          }
        break;
        case SDL_MOUSEBUTTONDOWN:
          mouse_button = SDL_GetMouseState (&x,&y);
          if (mouse_button & SDL_BUTTON(1)) {
            if (x > 352) {
              set_tracking (x, y, screen, &(tol->cam2_green));
            }
            else {
              set_tracking (x, y, screen, &(tol->cam1_green)); 
            }
          }
          else {
            if (x > 352) {
              set_tracking (x, y, screen, &(tol->cam2_red));
            }
            else {
              set_tracking (x, y, screen, &(tol->cam1_red)); 
            }
          }
        break;
      }
    }
    cam_img = cvQueryFrame (capture);
    image = ipl_to_surface (cam_img);
    cam_img_2 = cvQueryFrame (capture_2);
    image_2 = ipl_to_surface (cam_img_2);
    easy_blit (0, 0, back, screen);
    if (do_blob == 1) {
      cam1_green = find (image, &(tol->cam1_green));
      cam1_red = find (image, &(tol->cam1_red));
      cam2_green = find (image_2, &(tol->cam2_green));
      cam2_red = find (image_2, &(tol->cam2_red));
      vision_targets = target (cam1_red, cam1_green, ALLIANCE_BLUE);
      print_blobs_lighter (image, cam1_green, 0, 150, 0);
      print_blobs_lighter (image, cam1_red, 150, 0, 0);
      print_blobs_lighter (image_2, cam2_green, 0, 150, 0);
      print_blobs_lighter (image_2, cam2_red, 150, 0, 0);
      if (vision_targets != NULL) {
        render_text (screen, arial, 100, 490, "Found target!");
        print_blobs (image, vision_targets, 0, 0, 0);
        free_blobs (vision_targets);
      }
    }
    if (do_text == 1) {
      render_text (screen, arial, 600, 308, "FPS: %d", (lastfps));
      //print_blobs (image_2, cam2_red, 0, 0, 0);
      render_text (screen, arial, 10, 308, "Hotkey list:");
      render_text (screen, arial, 20, 328, "i - increase left green blob minimum length: %d", tol->cam1_green.blob_minlength);
      render_text (screen, arial, 20, 348, "k - decrease left green blob minimum length");
      render_text (screen, arial, 20, 368, "o - increase left green check tolerance: %d", tol->cam1_green.blob_tolerance);
      render_text (screen, arial, 20, 388, "l - decrease left green check tolerance");
      render_text (screen, arial, 20, 408, "y - increase left red blob minimum length: %d", tol->cam1_red.blob_minlength);
      render_text (screen, arial, 20, 428, "h - decrease left red blob minimum length");
      render_text (screen, arial, 20, 448, "u - increase left red check tolerance: %d", tol->cam1_red.blob_tolerance);
      render_text (screen, arial, 20, 468, "j - decrease left red check tolerance");
      render_text (screen, arial, 50, 508, "Green check color: %d, %d, %d", tol->cam1_green.r, tol->cam1_green.g, tol->cam1_green.b);
      SPG_RectFilled (screen, 20, 500, 40, 520, SDL_MapRGB (screen->format, tol->cam1_green.r, tol->cam1_green.g, tol->cam1_green.b));
      render_text (screen, arial, 50, 548, "Red check color: %d, %d, %d", tol->cam1_red.r, tol->cam1_red.g, tol->cam1_red.b);
      SPG_RectFilled (screen, 20, 540, 40, 560, SDL_MapRGB (screen->format, tol->cam1_red.r, tol->cam1_red.g, tol->cam1_red.b));
      render_text (screen, arial, 320, 328, "w - increase right green blob minimum length: %d", tol->cam2_green.blob_minlength);
      render_text (screen, arial, 320, 348, "s - decrease right green blob minimum length");
      render_text (screen, arial, 320, 368, "e - increase right green check tolerance: %d", tol->cam2_green.blob_tolerance);
      render_text (screen, arial, 320, 388, "d - decrease right green check tolerance");
      render_text (screen, arial, 320, 408, "r - increase right red blob minimum length: %d", tol->cam2_red.blob_minlength);
      render_text (screen, arial, 320, 428, "f - decrease right red blob minimum length");
      render_text (screen, arial, 320, 448, "t - increase right red check tolerance: %d", tol->cam2_red.blob_tolerance);
      render_text (screen, arial, 320, 468, "g - decrease right red check tolerance");
      render_text (screen, arial, 350, 508, "Green check color: %d, %d, %d", tol->cam2_green.r, tol->cam2_green.g, tol->cam2_green.b);
      SPG_RectFilled (screen, 320, 500, 340, 520, SDL_MapRGB (screen->format, tol->cam2_green.r, tol->cam2_green.g, tol->cam2_green.b));
      render_text (screen, arial, 350, 548, "Red check color: %d, %d, %d", tol->cam2_red.r, tol->cam2_red.g, tol->cam2_red.b);
      SPG_RectFilled (screen, 320, 540, 340, 560, SDL_MapRGB (screen->format, tol->cam2_red.r, tol->cam2_red.g, tol->cam2_red.b));
      if ((cam1_green != NULL) && (cam2_green != NULL)) {
        a1 = image_angle (cam1_green->center_x);
        a2 = image_angle (cam2_green->center_x);
        render_text (screen, arial, 580, 348, "Image 1 centroid: %d, %d", cam1_green->center_x, cam1_green->center_y);
        render_text (screen, arial, 580, 368, "Image 2 centroid: %d, %d", cam2_green->center_x, cam2_green->center_y);
        render_text (screen, arial, 580, 388, "Depth, Method 1: %f", find_depth (a1, a2, 0));
        render_text (screen, arial, 580, 408, "Depth, Method 2: %f", find_depth (a1, a2, 1));
        render_text (screen, arial, 580, 428, "Depth, Method 3: %f", find_depth (a1, a2, 2));
        render_text (screen, arial, 580, 448, "Angle, Left: %f", a1 * (180/PI));
        render_text (screen, arial, 580, 468, "Angle, Right: %f", a2 * (180/PI));
        SPG_RectFilled (screen, 780, (int)(35 * find_depth (a1, a2, 2)) - 300, 800, 20 + (int)(35 * find_depth (a1, a2, 1)) - 300, SDL_MapRGB (screen->format, tol->cam2_green.r, tol->cam2_green.g, tol->cam2_green.b));
      }
    }
    if (do_blob == 1) {
      free_blobs (cam1_green);
      free_blobs (cam1_red);
      free_blobs (cam2_green);
      free_blobs (cam2_red);
    }
    easy_blit (0, 0, image, screen);
    easy_blit (352, 0, image_2, screen);
    SDL_FreeSurface (image);
    SDL_FreeSurface (image_2);
    SDL_Flip (screen);
    log_fp = fopen ("colors.tol", "wb");
    fwrite (&tol, sizeof (tolerance_file_t), 1, log_fp);
    fclose (log_fp);
  }
  return 0;
}
Beispiel #3
0
int gui_init (void) {
#if 0
	if (display == NULL) {
		SDL_Init (SDL_INIT_VIDEO | SDL_INIT_JOYSTICK);
		display = SDL_SetVideoMode(640,480,16,VIDEO_FLAGS);
#if SDL_UI_DEBUG > 0
		write_log ("SDLUI: SDL_Init display init\n");
#endif
	} else {
#if SDL_UI_DEBUG > 0
		write_log ("SDLUI: SDL_Init display ready\n");
#endif
	}
#endif

	SDL_JoystickEventState(SDL_ENABLE);
	SDL_JoystickOpen(0);
	SDL_ShowCursor(SDL_DISABLE);
  	TTF_Init();

	amiga_font = TTF_OpenFont("guidep/fonts/amiga4ever_pro2.ttf", 16);
	if (!amiga_font) {
	    printf("SDLUI: TTF_OpenFont failed: %s\n", TTF_GetError());
		abort();
	}
	text_color.r = 50;
	text_color.g = 50;
	text_color.b = 50;

	if(!pMainMenu_Surface) pMainMenu_Surface = SDL_LoadBMP("guidep/images/menu.bmp");
	menu_load_surface(pMainMenu_Surface);
	if (pMenu_Surface == NULL) {
		write_log ("SDLUI: Failed to load menu image\n");
		abort();
	}
	pMouse_Pointer	= SDL_LoadBMP("guidep/images/mousep_33x33_wb20.bmp");
	if (pMouse_Pointer == NULL) {
		write_log ("SDLUI: Failed to load mouse pointer image\n");
		abort();
	}
	SDL_SetColorKey(pMouse_Pointer, SDL_SRCCOLORKEY, SDL_MapRGB(pMouse_Pointer->format, 68, 94, 174));

	icon_expansion		= SDL_LoadBMP("guidep/images/icon-expansion.bmp");
	if (icon_expansion == NULL) {
		write_log ("SDLUI: Failed to load icon expansion\n");
		abort();
	}
	icon_preferences	= SDL_LoadBMP("guidep/images/icon-preferences.bmp");
	if (icon_preferences == NULL) {
		write_log ("SDLUI: Failed to load icon preferences\n");
		abort();
	}
	icon_keymaps		= SDL_LoadBMP("guidep/images/icon-keymaps.bmp");
	if (icon_keymaps == NULL) {
		write_log ("SDLUI: Failed to load icon keymaps\n");
		abort();
	}
	icon_floppy			= SDL_LoadBMP("guidep/images/icon-floppy.bmp");
	if (icon_floppy == NULL) {
		write_log ("SDLUI: Failed to load icon floppy\n");
		abort();
	}
	icon_reset			= SDL_LoadBMP("guidep/images/icon-reset.bmp");
	if (icon_reset == NULL) {
		write_log ("SDLUI: Failed to load icon reset\n");
		abort();
	}
	icon_storage		= SDL_LoadBMP("guidep/images/icon-storage.bmp");
	if (icon_storage == NULL) {
		write_log ("SDLUI: Failed to load icon storage\n");
		abort();
	}
	icon_run			= SDL_LoadBMP("guidep/images/icon-run.bmp");
	if (icon_run == NULL) {
		write_log ("SDLUI: Failed to load icon run\n");
		abort();
	}
	icon_exit			= SDL_LoadBMP("guidep/images/icon-exit.bmp");
	if (icon_exit == NULL) {
		write_log ("SDLUI: Failed to load icon exit\n");
		abort();
	}
//	icon_tweaks			= SDL_LoadBMP("guidep/images/icon-tweaks.bmp");

	return 1;
}
Beispiel #4
0
int main(int argc, char **argv)
{
	int res = 0;

#else

/* gee */
extern "C" DECLSPEC void SDLCALL SDL_SetModuleHandle(void *hInst);

// translated to utf8_main
int main(int argc, char *argv[])
{
	int res = 0;

#if	!(SDLMAME_SDL2)
	/* Load SDL dynamic link library */
	if ( SDL_Init(SDL_INIT_NOPARACHUTE) < 0 ) {
		fprintf(stderr, "WinMain() error: %s", SDL_GetError());
		return(FALSE);
	}
	SDL_SetModuleHandle(GetModuleHandle(NULL));
#endif
#endif
	// disable I/O buffering
	setvbuf(stdout, (char *) NULL, _IONBF, 0);
	setvbuf(stderr, (char *) NULL, _IONBF, 0);

	#ifdef SDLMAME_UNIX
	#if (!defined(SDLMAME_MACOSX)) && (!defined(SDLMAME_HAIKU))
	if (TTF_Init() == -1)
	{
		printf("SDL_ttf failed: %s\n", TTF_GetError());
	}
	FcInit();
	#endif
	#endif

	#ifdef SDLMAME_OS2
	MorphToPM();
	#endif

#if defined(SDLMAME_X11) && (SDL_MAJOR_VERSION == 1) && (SDL_MINOR_VERSION == 2)
	if (SDL_Linked_Version()->patch < 10)
	/* workaround for SDL choosing a 32-bit ARGB visual */
	{
		Display *display;
		if ((display = XOpenDisplay(NULL)) && (DefaultDepth(display, DefaultScreen(display)) >= 24))
		{
			XVisualInfo vi;
			char buf[130];
			if (XMatchVisualInfo(display, DefaultScreen(display), 24, TrueColor, &vi)) {
				snprintf(buf, sizeof(buf), "0x%lx", vi.visualid);
				osd_setenv(SDLENV_VISUALID, buf, 0);
			}
		}
		if (display)
			XCloseDisplay(display);
	}
#endif

	{
		sdl_osd_interface osd;
		sdl_options options;
		cli_frontend frontend(options, osd);
		res = frontend.execute(argc, argv);
	}

#ifdef MALLOC_DEBUG
	{
		void check_unfreed_mem(void);
		check_unfreed_mem();
	}
#endif

	// already called...
	//SDL_Quit();

	#ifdef SDLMAME_UNIX
	#if (!defined(SDLMAME_MACOSX)) && (!defined(SDLMAME_HAIKU))
	TTF_Quit();
	FcFini();
	#endif
	#endif

	exit(res);

	return res;
}
Beispiel #5
0
int main( int argc, char* args[] )
{
	
	//Start	SDL
	SDL_Init( SDL_INIT_EVERYTHING );	
	TTF_Init();

	//Set window caption
	SDL_WM_SetCaption("Yet Another Dave!", NULL);

	SDL_Surface *buffer = NULL;
	SDL_Surface *message = NULL;

	bool fullscreen = false;

	if( fullscreen == true )	
		buffer = SDL_SetVideoMode( 640, 480, 32, SDL_SWSURFACE | SDL_FULLSCREEN);
	else
		buffer = SDL_SetVideoMode( 640, 480, 32, SDL_SWSURFACE );
	
	SDL_Event event ;

	Game *G1 = new Game();
	player *P1 = new player();
	
	int times=0;
	

	while(event.type != SDL_QUIT)
	{
		SDL_PollEvent( &event );
		//If a key was pressed 
		if( event.type == SDL_KEYDOWN )
		{
			//Set the proper message surface 
			switch( event.key.keysym.sym ) 
			{ 
				case SDLK_UP:   if(times==0&&G1->jump==0) times=10;//P1->movePlayer(G1, 2);
								G1->jump=1;
								break; 
				case SDLK_DOWN:	P1->movePlayer(G1, 3);		
								break; 
				case SDLK_LEFT: P1->movePlayer(G1, 0);	
								break; 
				case SDLK_RIGHT: P1->movePlayer(G1, 1);
								break;
				
				
			}			
		}
		if(times>0)
		{
			times--;
			P1->movePlayer(G1, 2);
		}
		else
		{
			G1->jump=1;
			P1->movePlayer(G1, 3);	
		}
		G1->blitBackground( buffer );				
		G1->blitExtra( buffer );
		P1->blitPlayer( buffer );
		G1->blitMessage( buffer );
		SDL_Flip( buffer );

		SDL_Delay(100);
		if(G1->end(P1))
			break;		
	}
	G1->blitBackground( buffer );
	G1->blitExtra( buffer );
	SDL_Flip( buffer );
	static const SDL_Color WHITE = {255,255,255} ;
	TTF_Font *font;
	SDL_Color textColor;	
	font = TTF_OpenFont( "comic.ttf", 24 );
	textColor = WHITE;
	SDL_Rect *r1=new SDL_Rect();
	r1->x=296; r1->y=228;
	message = TTF_RenderText_Solid( font, "GAME OVER", textColor );
	SDL_BlitSurface(message, NULL, buffer, r1);
	SDL_Flip( buffer );
	r1->x=250; r1->y=260;
	message = TTF_RenderText_Solid( font, "Final Score: ", textColor );
	SDL_BlitSurface(message, NULL, buffer, r1);
	SDL_Flip( buffer );
	char buff[10];
	_itoa_s(G1->score,buff,10);
	r1->x=400; r1->y=260;
	message = TTF_RenderText_Solid( font, buff, textColor );
	SDL_BlitSurface(message, NULL, buffer, r1);
	SDL_Flip( buffer );
	r1->x=50; r1->y=0;
	message = TTF_RenderText_Solid( font, "Thank You for Playing", textColor );
	SDL_BlitSurface(message, NULL, buffer, r1);
	SDL_Flip( buffer );
	r1->x=0; r1->y=28;
	message = TTF_RenderText_Solid( font, "Game Developed by Chinmay Pednekar", textColor );
	SDL_BlitSurface(message, NULL, buffer, r1);
	SDL_Flip( buffer );
	while(event.type != SDL_QUIT)
		SDL_PollEvent( &event );

	/*SDL_Rect *bcrop=new SDL_Rect();
	bcrop->x=0;
	bcrop->y=0;
	bcrop->h=480;
	bcrop->w=640;
		
	SDL_Rect *crop=new SDL_Rect();
	crop->x=96;
	crop->y=0;
	crop->h=32;
	crop->w=24;
	
	SDL_Rect *locn=new SDL_Rect();
	locn->x=32;
	locn->y=416;
	locn->h=32;
	locn->w=24;
	
	int lpos=24,rpos=72;
		
	while(event.type != SDL_QUIT)
	{
		SDL_PollEvent( &event );
		//If a key was pressed 
		if( event.type == SDL_KEYDOWN )
		{
			//Set the proper message surface 
			switch( event.key.keysym.sym ) 
			{ 
				case SDLK_UP: 
					if(locn->y>72) locn->y-=8;
								break; 
				case SDLK_DOWN:
					if(locn->y<416) locn->y+=8;
								break; 
				case SDLK_LEFT: 
					if(locn->x>240) locn->x-=8;
					else
					{
						if(bcrop->x>0) bcrop->x-=8;
						else if(locn->x>32) locn->x-=8;
					}
					if(lpos==0)
					{
						lpos=1;
						crop->x=0;
					}
					else
					{
						lpos=0;
						crop->x=24;
					}
								break; 
				case SDLK_RIGHT:
					if(locn->x<320) locn->x+=8;
					else
					{
						if(bcrop->x<640) bcrop->x+=8;
						else if(locn->x<584) locn->x+=8;
					}
					if(rpos==0)
					{
						rpos=1;
						crop->x=96;
					}
					else
					{
						rpos=0;
						crop->x=72;
					}
								break; 
			}
			
			
		}
		 
			SDL_BlitSurface( back, bcrop, buffer, NULL );
			SDL_BlitSurface( image, crop, buffer, locn );
			SDL_Flip( buffer );
	
			SDL_Delay(100);
		

			SDL_BlitSurface( back, bcrop, buffer, NULL );
			SDL_Flip( buffer );

	}
	*/
	/* Free up space afterwards */
	SDL_FreeSurface( buffer );
	
	//Quit 	SDL
	SDL_Quit();
	return 0;
}
Beispiel #6
0
int main(int argc, char **argv){
	if (SDL_Init(SDL_INIT_EVERYTHING) != 0){
		logSDLError(std::cout, "SDL_Init");
		return 1;
	}

	if (TTF_Init() != 0){
	logSDLError(std::cout, "TTF_Init");
	return 1;
	}

	SDL_Window *window = SDL_CreateWindow("Hello World!", 100, 100, SCREEN_WIDTH, GRID_HEIGHT + HUD_HEIGHT,
	SDL_WINDOW_SHOWN);
	if (window == nullptr){
		logSDLError(std::cout, "CreateWindow");
		SDL_Quit();
		return 2;
	}

	SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
	if (renderer == nullptr){
		logSDLError(std::cout, "CreateRenderer");
		SDL_DestroyWindow(window);
		SDL_Quit();
		return 3;
	}

	//The textures we'll be using
	SDL_Texture *background = loadTexture("res/game_bg.jpg", renderer);
	SDL_Texture *image = loadTexture("res/Blue.png", renderer);
	SDL_Texture *blueGem = loadTexture("res/Blue.png", renderer);
	SDL_Texture *greenGem = loadTexture("res/Green.png", renderer);
	SDL_Texture *purpleGem = loadTexture("res/Purple.png", renderer);
	SDL_Texture *redGem = loadTexture("res/Red.png", renderer);
	SDL_Texture *yellowGem = loadTexture("res/Yellow.png", renderer);
	SDL_Texture *gems[] = {blueGem, greenGem, purpleGem, redGem, yellowGem};
	SDL_Texture *cursorYellowImg = loadTexture("res/cursor_yellow.png", renderer);
	SDL_Texture *cursorGreenImg = loadTexture("res/cursor_green.png", renderer);
	//Make sure they both loaded ok
	if (background == nullptr || image == nullptr){
		SDL_DestroyRenderer(renderer);
		SDL_DestroyWindow(window);
		SDL_Quit();
		return 4;
	}

	//We'll render the string "TTF fonts are cool!" in white
	//Color is in RGB format
	SDL_Color color = { 255, 255, 255 };
	SDL_Texture *textImage;
	TTF_Font* font = loadFont("res/sample.ttf", 32);

	//Our event structure
	SDL_Event e;
	//For tracking if we want to quit
	bool quit = false;
	int gameState = GAMESTATE_TITLE_SCREEN;
	int** pGridArray;
	gem* pGemsArray = new gem[NUM_ROWS * NUM_COLUMNS];

	int score;

	int mouseX = 0;
	int mouseY = 0;
	int numGemsSelected = 0;
	int selectedGems[2][2] = {{-1, -1}, {-1, -1}};
	bool gemSelected = false;
	int cursorRow = 0;
	int cursorColumn = 0;
	bool foundMatch = false;
	int thisRow, thisColumn;
	bool gemsDropping;
	bool cancelSwap = false;
	bool mouseDown = false;
	int dragStartX;
	int dragStartY;
	bool dragStarted = false;
	time_t timer;
	time_t startTime;
	std::ostringstream os;

	while (!quit)
	{
		switch (gameState)
		{
			case GAMESTATE_TITLE_SCREEN:
			break;

			case GAMESTATE_INIT:
				for (int i = 0; i < NUM_ROWS*NUM_COLUMNS; i++)
				{
					pGemsArray[i].state = GEMSTATE_IDLE;
				}
				pGridArray = initGrid(pGemsArray);
				score = 0;
				startTime = time(0);
				gameState = GAMESTATE_INITIAL_CHECK_MATCH;
			break;

			case GAMESTATE_INITIAL_CHECK_MATCH:
				SDL_Delay(1000);
				checkMatchAllRows(pGridArray, pGemsArray, &score);
				gameState = GAMESTATE_CHECKDROP;
			break;

			case GAMESTATE_CHECK_MATCH:

				foundMatch = false;
				for (int row = NUM_ROWS-1; row >= 0; row--)
				{
					for (int column = 0; column < NUM_COLUMNS; column++)
					{
						if (pGemsArray[pGridArray[row][column]].prevState == GEMSTATE_FALL)
						{
							foundMatch = checkMatchAfterSwap(pGridArray, pGemsArray, &pGemsArray[pGridArray[row][column]], &score);
						}
					}
				}

				gameState = GAMESTATE_CHECKDROP;

				for (int row = NUM_ROWS-1; row >= 0; row--)
				{
					for (int column = 0; column < NUM_COLUMNS; column++)
					{
						pGemsArray[pGridArray[row][column]].prevState = -1;
					}
				}

			break;

			case GAMESTATE_AWAIT_INPUT:

				if (gemSelected)
				{
					if (numGemsSelected < 2)
					{
						numGemsSelected++;
					}
					else
					{
						numGemsSelected = 0;
					}
					cursorRow = (mouseY-HUD_HEIGHT) / ROW_HEIGHT;
					cursorColumn = mouseX / COLUMN_WIDTH;

					// Store the location of the selected gem
					selectedGems[numGemsSelected-1][ROW] = cursorRow;
					selectedGems[numGemsSelected-1][COLUMN] = cursorColumn; 

					gemSelected = false;

					// Check if ready to swap
					if (numGemsSelected == 2)
					{
						int state = checkSwapGems((int*)selectedGems);
						state = setSwapGems(state, pGemsArray, pGridArray, selectedGems[0][ROW], selectedGems[0][COLUMN], selectedGems[1][ROW], selectedGems[1][COLUMN]);
						if (state == -1)
						{

							// Remove all cursors
							numGemsSelected = 0;

							// Set new cursor to this position
							cursorRow = (mouseY-HUD_HEIGHT) / ROW_HEIGHT;
							cursorColumn = mouseX / COLUMN_WIDTH;

							// Store the location of the selected gem
							selectedGems[numGemsSelected-1][ROW] = cursorRow;
							selectedGems[numGemsSelected-1][COLUMN] = cursorColumn; 
							gemSelected = true;
						}
						else
						{
							gameState = state;
						}
					}
				}
				
			break;


			case GAMESTATE_SWAP_LEFT:
			case GAMESTATE_SWAP_RIGHT:

				thisRow = selectedGems[0][ROW];
				if (gameState == GAMESTATE_SWAP_LEFT)
					thisColumn = selectedGems[0][COLUMN];
				else
					thisColumn = selectedGems[1][COLUMN];

				pGemsArray[pGridArray[thisRow][thisColumn]].x += pGemsArray[pGridArray[thisRow][thisColumn]].velocity;
				pGemsArray[pGridArray[thisRow][thisColumn-1]].x += pGemsArray[pGridArray[thisRow][thisColumn-1]].velocity;
				
				if (pGemsArray[pGridArray[thisRow][thisColumn]].x <= -COLUMN_WIDTH)
				{
					numGemsSelected = 0;

					// Swap with other gem
					int temp = pGridArray[thisRow][thisColumn];
					pGridArray[thisRow][thisColumn] = pGridArray[thisRow][thisColumn-1];
					pGridArray[thisRow][thisColumn-1] = temp;

					pGemsArray[pGridArray[thisRow][thisColumn]].velocity = 0;
					pGemsArray[pGridArray[thisRow][thisColumn]].x = 0;
					pGemsArray[pGridArray[thisRow][thisColumn]].column++;
					pGemsArray[pGridArray[thisRow][thisColumn]].state = GEMSTATE_IDLE;
					
					pGemsArray[pGridArray[thisRow][thisColumn-1]].velocity = 0;
					pGemsArray[pGridArray[thisRow][thisColumn-1]].x = 0;
					pGemsArray[pGridArray[thisRow][thisColumn-1]].column--;
					pGemsArray[pGridArray[thisRow][thisColumn-1]].state = GEMSTATE_IDLE;

					bool foundMatch = false;
					bool foundMatch2 = false;
					if (!cancelSwap)
					{
						foundMatch = checkMatchAfterSwap(pGridArray, pGemsArray, &pGemsArray[pGridArray[thisRow][thisColumn]], &score);
						foundMatch2 = checkMatchAfterSwap(pGridArray, pGemsArray, &pGemsArray[pGridArray[thisRow][thisColumn-1]], &score);
					}

					if (foundMatch || foundMatch2)
					{
						gameState = GAMESTATE_CHECKDROP;
					}
					else
					{
						if (cancelSwap)
						{
							// Gems have gone back to their original positions after cancelling the swap
							cancelSwap = false;
							gameState = GAMESTATE_AWAIT_INPUT;
						}
						else
						{
							// Swap the gems back to their original positions
							gameState = setSwapGems(gameState, pGemsArray, pGridArray, selectedGems[0][ROW], selectedGems[0][COLUMN], selectedGems[1][ROW], selectedGems[1][COLUMN]);
							cancelSwap = true;
						}
	
					}
				}					
			break;

			case GAMESTATE_SWAP_UP:
			case GAMESTATE_SWAP_DOWN:

				thisColumn = selectedGems[0][COLUMN];
				if (gameState == GAMESTATE_SWAP_UP)
					thisRow = selectedGems[0][ROW];
				else
					thisRow = selectedGems[1][ROW];

				pGemsArray[pGridArray[thisRow][thisColumn]].y += pGemsArray[pGridArray[thisRow][thisColumn]].velocity;
				pGemsArray[pGridArray[thisRow-1][thisColumn]].y += pGemsArray[pGridArray[thisRow-1][thisColumn]].velocity;
				
				if (pGemsArray[pGridArray[thisRow][thisColumn]].y <= -ROW_HEIGHT)
				{
					numGemsSelected = 0;
					
					// Swap with other gem
					int temp = pGridArray[thisRow][thisColumn];
					pGridArray[thisRow][thisColumn] = pGridArray[thisRow-1][thisColumn];
					pGridArray[thisRow-1][thisColumn] = temp;

					pGemsArray[pGridArray[thisRow][thisColumn]].velocity = 0;
					pGemsArray[pGridArray[thisRow][thisColumn]].y = 0;
					pGemsArray[pGridArray[thisRow][thisColumn]].row++;
					pGemsArray[pGridArray[thisRow][thisColumn]].state = GEMSTATE_IDLE;

					pGemsArray[pGridArray[thisRow-1][thisColumn]].velocity = 0;
					pGemsArray[pGridArray[thisRow-1][thisColumn]].y = 0;
					pGemsArray[pGridArray[thisRow-1][thisColumn]].row--;
					pGemsArray[pGridArray[thisRow-1][thisColumn]].state = GEMSTATE_IDLE;

					bool foundMatch = false;
					bool foundMatch2 = false;
					if (!cancelSwap)
					{
						foundMatch = checkMatchAfterSwap(pGridArray, pGemsArray, &pGemsArray[pGridArray[thisRow][thisColumn]], &score);
						foundMatch2 = checkMatchAfterSwap(pGridArray, pGemsArray, &pGemsArray[pGridArray[thisRow-1][thisColumn]], &score);
					}

					if (foundMatch || foundMatch2)
					{
						gameState = GAMESTATE_CHECKDROP;
					}
					else
					{					
						if (cancelSwap)
						{
							// Gems have gone back to their original positions after cancelling the swap
							cancelSwap = false;
							gameState = GAMESTATE_AWAIT_INPUT;
						}
						else
						{
							// Swap the gems back to their original positions
							gameState = setSwapGems(gameState, pGemsArray, pGridArray, selectedGems[0][ROW], selectedGems[0][COLUMN], selectedGems[1][ROW], selectedGems[1][COLUMN]);
							cancelSwap = true;
						}
					}
				}					
			break;

			case GAMESTATE_CHECKDROP:

				if (checkDrop(pGridArray, pGemsArray))
				{
					gameState = GAMESTATE_DROP;
				}
				else
				{
					gameState = GAMESTATE_ADD_GEMS;
				}

			break;

			case GAMESTATE_DROP:

				// Check if any more gems are dropping
				gemsDropping = false;
				for (int i = 0; i < NUM_ROWS * NUM_COLUMNS; i++)
				{
					if (pGemsArray[i].state == GEMSTATE_FALL || pGemsArray[i].state == GEMSTATE_ENTER || pGemsArray[i].state == GEMSTATE_BOUNCE)
					{
						gemsDropping = true;
						break;
					}
				}

				if (!gemsDropping)
				{
					gameState = GAMESTATE_CHECK_MATCH;
				}
			break;


			case GAMESTATE_GAME_OVER:

				if (timer - startTime >= GAME_OVER_TIMEOUT)
				{
					gameState = GAMESTATE_TITLE_SCREEN;
					startTime = time(0);
				}
			break;

			case GAMESTATE_ADD_GEMS:

				srand(time(NULL));
				bool gemsAdded = false;
				// Find empty columns
				for (int column = 0; column < NUM_COLUMNS; column++)
				{
					// Find empty spaces in this column starting from top
					int row = 0;
					
					while (pGemsArray[pGridArray[row][column]].type == -1)
					{
						pGemsArray[pGridArray[row][column]].type = rand() % NUM_GEM_TYPES;
						pGemsArray[pGridArray[row][column]].state = GEMSTATE_ENTER;
						pGemsArray[pGridArray[row][column]].row = 0;
						pGemsArray[pGridArray[row][column]].column = column;
						pGemsArray[pGridArray[row][column]].y = -(ROW_HEIGHT+10)*(NUM_ROWS - row);
						pGemsArray[pGridArray[row][column]].velocity = 1;
						pGemsArray[pGridArray[row][column]].dropToRow = row;
						pGemsArray[pGridArray[row][column]].prevState = GEMSTATE_FALL;
						row++;
						gemsAdded = true;
					}
				}

				numGemsSelected = 0;
				if (gemsAdded)
				{
					gameState = GAMESTATE_DROP;
				}
				else
				{
					gameState = GAMESTATE_AWAIT_INPUT;
				}
			break;

		}

		if (gameState != GAMESTATE_TITLE_SCREEN)
		{

			for (int row = NUM_ROWS-1; row >= 0; row--)
			{
				for (int column = 0; column < NUM_COLUMNS; column++)
				{
					gem* thisGem = &pGemsArray[pGridArray[row][column]];

					switch (pGemsArray[pGridArray[row][column]].state)
					{
						case GEMSTATE_IDLE:
						break;

						case GEMSTATE_FALL:
						case GEMSTATE_ENTER:

							if ((pGemsArray[pGridArray[row][column]].type != -1 && pGemsArray[pGridArray[row+1][column]].type == -1) ||
								pGemsArray[pGridArray[row][column]].state == GEMSTATE_ENTER)
							{
								dropGem(pGridArray, &pGemsArray[pGridArray[row][column]], pGemsArray);
							}
						break;

						case GEMSTATE_BOUNCE:

							thisGem->y += thisGem->velocity;
							thisGem->velocity--;		

							if (thisGem->y <= 0)
							{
								thisGem->y = 0;
								thisGem->velocity = 0;
								thisGem->state = GEMSTATE_IDLE;
							}
						break;
					}	
				}
			}
		}
	

		timer = time(0);

		if (gameState != GAMESTATE_TITLE_SCREEN && gameState != GAMESTATE_GAME_OVER && timer - startTime >= TIMEOUT)
		{
			gameState = GAMESTATE_GAME_OVER;
			startTime = time(0);
		}

		//Read user input & handle it
		//Read any events that occured, for now we'll just quit if any event occurs
		while (SDL_PollEvent(&e)){
			//If user closes the window
			if (e.type == SDL_QUIT){
				quit = true;
			}
			//If user clicks the mouse
			if (e.type == SDL_MOUSEBUTTONDOWN){
				if (gameState == GAMESTATE_TITLE_SCREEN)
				{
					gameState = GAMESTATE_INIT;
				}
				else
				{
					mouseX = e.button.x;
					mouseY = e.button.y;
					mouseDown = true;
					dragStartX = mouseX;
					dragStartY = mouseY;
					dragStarted = false;
				}
			}
			if (e.type == SDL_MOUSEBUTTONUP){
				if (gameState != GAMESTATE_TITLE_SCREEN)
				{
					mouseDown = false;
					gemSelected = true;
				}
			}
			if (e.type == SDL_MOUSEMOTION && mouseDown)
			{
				if (e.motion.xrel < 0)		// Dragged left
				{
					if (mouseX - e.motion.x > DRAG_DEAD_ZONE && !dragStarted)
					{
						// Start a new selection
						numGemsSelected = 0;
						dragStarted = true;
						gemSelected = true;
					}				
					 else if (mouseX - e.motion.x > DRAG_DEAD_ZONE && dragStarted)
					{
						// Select next gem
						mouseX -= COLUMN_WIDTH;
						mouseDown = false;
						gemSelected = true;
					}
				}
				else if (e.motion.xrel > 0)		// Dragged right
				{
					if (e.motion.x - mouseX > DRAG_DEAD_ZONE && !dragStarted)
					{
						numGemsSelected = 0;
						dragStarted = true;
						gemSelected = true;
					}				
					 else if (e.motion.x - mouseX > DRAG_DEAD_ZONE && dragStarted)
					{
						mouseX += COLUMN_WIDTH;
						mouseDown = false;
						gemSelected = true;
					}
				}
				else if (e.motion.yrel < 0)		// Dragged up
				{
					if (mouseY - e.motion.y > DRAG_DEAD_ZONE && !dragStarted)
					{
						numGemsSelected = 0;
						dragStarted = true;
						gemSelected = true;
					}				
					 else if (mouseY - e.motion.y > DRAG_DEAD_ZONE && dragStarted)
					{
						mouseY -= ROW_HEIGHT;
						mouseDown = false;
						gemSelected = true;
					}
				}
				else if (e.motion.yrel > 0)		// Dragged down
				{
					if (e.motion.y - mouseY > DRAG_DEAD_ZONE && !dragStarted)
					{
						numGemsSelected = 0;
						dragStarted = true;
						gemSelected = true;
					}				
					 else if (e.motion.y - mouseY > DRAG_DEAD_ZONE && dragStarted)
					{
						mouseY += ROW_HEIGHT;
						mouseDown = false;
						gemSelected = true;
					}
				}
			}
		}

		//Render scene

		//First clear the renderer
		SDL_RenderClear(renderer);

		//Get the width and height from the texture so we know how much to move x,y by
		//to tile it correctly
		int bW, bH;
		SDL_QueryTexture(background, NULL, NULL, &bW, &bH);

		int x;
		int y;
		//Draw the background
		renderTexture(background, renderer, 0, 0);

		if (gameState != GAMESTATE_TITLE_SCREEN && gameState != GAMESTATE_INIT)
		{
			// Draw the gems
			// int rowHeight = GRID_HEIGHT / NUM_ROWS;
			int gemWidth, gemHeight;
			SDL_QueryTexture(gems[0], NULL, NULL, &gemWidth, &gemHeight);

			// Draw cursors
			if (numGemsSelected > 0)
			{
				int cursorWidth, cursorHeight;
				SDL_QueryTexture(cursorYellowImg, NULL, NULL, &cursorWidth, &cursorHeight);
				renderTexture(cursorYellowImg, renderer, 
					selectedGems[0][COLUMN] * COLUMN_WIDTH + COLUMN_WIDTH/2 - cursorWidth/2, 
					selectedGems[0][ROW] * ROW_HEIGHT + ROW_HEIGHT/2 - cursorHeight/2 + HUD_HEIGHT);
			
				if (numGemsSelected == 2)
				{
					renderTexture(cursorGreenImg, renderer, 
						selectedGems[1][COLUMN] * COLUMN_WIDTH + COLUMN_WIDTH/2 - cursorWidth/2, 
						selectedGems[1][ROW] * ROW_HEIGHT + ROW_HEIGHT/2 - cursorHeight/2 + HUD_HEIGHT);
				}
			}

			for (int i = 0; i < NUM_ROWS * NUM_COLUMNS; i++)
			{
				if (pGemsArray[i].type != -1)
				{
					x = COLUMN_WIDTH * pGemsArray[i].column + COLUMN_WIDTH/2 - gemWidth/2;
					y = ROW_HEIGHT * pGemsArray[i].row + ROW_HEIGHT/2 - gemHeight/2 + HUD_HEIGHT;
					renderTexture(gems[pGemsArray[i].type], renderer, x + pGemsArray[i].x, y + pGemsArray[i].y);
				}
			}
		}

		
		// Draw text
		int iW, iH;
		switch (gameState)
		{
			case GAMESTATE_TITLE_SCREEN:
		
			os.str("");
			os.clear();
			os << "Click mouse to start";

			textImage = renderText(os.str(), font, color, renderer);
			if (textImage == nullptr){
				return 1;
			}

			SDL_QueryTexture(textImage, NULL, NULL, &iW, &iH);
			SDL_QueryTexture(textImage, NULL, NULL, &iW, &iH);
			x = SCREEN_WIDTH/2 - iW/2;
			y = GRID_HEIGHT/2;
			renderTexture(textImage, renderer, x, y);

			break;

			case GAMESTATE_GAME_OVER:

				os.str("");
				os.clear();
				os << "GAME OVER. Your score is " << score;

				textImage = renderText(os.str(), font, color, renderer);
				if (textImage == nullptr){
					return 1;
				}

				SDL_QueryTexture(textImage, NULL, NULL, &iW, &iH);
				SDL_QueryTexture(textImage, NULL, NULL, &iW, &iH);
				x = SCREEN_WIDTH/2 - iW/2;
				y = GRID_HEIGHT/2;
				renderTexture(textImage, renderer, x, y);

			break;

			default:

				os.str("");
				os.clear();
				os << "Score " << score;

				textImage = renderText(os.str(), font, color, renderer);
				if (textImage == nullptr){
					return 1;
				}
				x = 10;
				y = 10;
				renderTexture(textImage, renderer, x, y);
				// drawText("Score ", score, renderer, textImage, font, color, 10, 10);


				os.str("");
				os.clear();
				os << "Time " << (TIMEOUT - (timer - startTime));
				textImage = renderText(os.str(), font, color, renderer);
				if (textImage == nullptr){
					return 1;
				}
				//Get the texture w/h so we can position it correctly on the screen
				SDL_QueryTexture(textImage, NULL, NULL, &iW, &iH);
				SDL_QueryTexture(textImage, NULL, NULL, &iW, &iH);
				x = SCREEN_WIDTH -10 - iW;
				renderTexture(textImage, renderer, x, y);

				// drawText seems to always draw to the left of the screen so commented out
				// drawText("Time ", timer - startTime, renderer, textImage, font, color, 100, 10);

			break;
		}

		//Update the screen
		SDL_RenderPresent(renderer);
	}

	//Clean up our objects and quit
	SDL_DestroyTexture(background);
	SDL_DestroyTexture(image);
	SDL_DestroyTexture(blueGem);
	SDL_DestroyTexture(greenGem);
	SDL_DestroyTexture(purpleGem);
	SDL_DestroyTexture(redGem);
	SDL_DestroyTexture(yellowGem);

	for (int i = 0; i < sizeof(*gems); i++)
	{
		gems[i] = NULL;
	}

	for (int row = 0; row < NUM_ROWS; row++)
	{
		delete [] pGridArray[row];
	}
	delete [] pGridArray;

	delete [] pGemsArray;

	SDL_DestroyRenderer(renderer);
	SDL_DestroyWindow(window);
	SDL_Quit();

	return 0;
}
Beispiel #7
0
int main(int argc, char *argv[]) {
    int width = 640;
    int height = 480;
 
    if (SDL_Init(SDL_INIT_VIDEO) != 0) {
    	return 1;
    }
    if (TTF_Init() == -1) {
      printf("Unable to initialize SDL_ttf: %s \n", TTF_GetError());
      return 2;
    }
    atexit(SDL_Quit);

    const SDL_VideoInfo* videoInfo = SDL_GetVideoInfo();
    if (videoInfo) {
      width = videoInfo->current_w;
      height = videoInfo->current_h;
    }

    SDL_Surface* screen = SDL_SetVideoMode(width, height, 0,
        SDL_HWSURFACE | SDL_FULLSCREEN | SDL_DOUBLEBUF);
    reflexgame::Renderer renderer(screen);
    reflexgame::GameState gameState(width, height);
 
    if (screen == NULL)
        return 2;

    SDL_ShowCursor(0);
    SDL_WM_GrabInput(SDL_GRAB_ON);

    Uint32 nextTime = 0;
    time_left(nextTime);
    gameState.start();
    while(true) {
        gameState.handleTick();
        if (gameState.gameEnded()) {
          SDL_Event event; 
          while(SDL_PollEvent(&event)) {
            switch(event.type){
              case SDL_KEYDOWN:
                switch(event.key.keysym.sym){
                  case SDLK_ESCAPE:
                    return 0;
                    break;
                  default:
                    break;
                }
              case SDL_QUIT:
                return 0;
              default:
                break;
            }
          }
          renderer.drawEndGame(gameState);
        } else {
          SDL_Event event; 
          while(SDL_PollEvent(&event)) {
            switch(event.type){
              case SDL_MOUSEBUTTONDOWN:
                {
                  if (event.button.button == SDL_BUTTON_LEFT) {
                    int x = event.button.x;
                    int y = event.button.y;
                    printf("Click at (%d, %d)\n", x, y);
                    gameState.attackAt(x, y);
                  }
                  break;
                }
              case SDL_KEYDOWN:
                switch(event.key.keysym.sym){
                  case SDLK_ESCAPE:
                    return 0;
                    break;
                  default:
                    break;
                }
              case SDL_QUIT:
                return 0;
              default:
                break;
            }
          }
          renderer.draw(gameState);
        }
        SDL_Flip(screen);
        SDL_Delay(time_left(nextTime));
    }
 
    return 0;
}
Beispiel #8
0
int main(int argc, char *argv[])
{
    Game *g = (Game*) malloc(sizeof(Game));
    SDL_Event event;
    Uint8 *keystates;
    Uint8 quit = false;
    long lastplayerupdate = ms_time();
    long lastenemyupdate = ms_time();
    long lastshotupdate = ms_time();
    long lastufoupdate = ms_time();
    
    srand((unsigned int) time(NULL));
    
    // SDL initialisieren
    if (SDL_Init(SDL_INIT_VIDEO) == -1) {
        printf("Kann Video nicht initialisieren: %s\n", SDL_GetError());
        exit(1);
    }
    
    atexit(SDL_Quit);
    
    g->screen = SDL_SetVideoMode(WIDTH, HEIGHT, 16, SDL_HWSURFACE);
    
    if (g->screen == NULL) {
        printf("Kann Video-Modus nicht festlegen: %s\n", SDL_GetError());
        exit(1);
    }
    
    TTF_Init();
    
    
    // Game initialisieren
    initGame(g);
    startNewLevel(g);
    updateScore(g);
    updateLives(g);
    showHighscore(g);
    updateBlocks(g);
    
    // Nächster Grafikzustand
    SDL_Flip(g->screen);
    
    // Loop
    while (!quit) {
        // SDL Events abfragen
        SDL_PollEvent(&event);
        
        // Tastenstatus laden
        keystates = SDL_GetKeyState(NULL);
        
        // Escape gedrückt -> beenden
        // TODO: Menü aufrufen statt beenden
        if (keystates[SDLK_ESCAPE]) {
            saveHighscore(g->score);
            quit = true;
        }
        
        // Nur wenn entweder Links oder Rechts, nicht beide zur selben Zeit
        if (keystates[SDLK_LEFT] != keystates[SDLK_RIGHT] && lastplayerupdate >= 100) {
            lastplayerupdate = ms_time();
            
            // Links
            if (keystates[SDLK_LEFT]) {
                movePlayer(g, Left);
            }
            // Rechts
            if (keystates[SDLK_RIGHT]) {
                movePlayer(g, Right);
            }
        }
        
        if (keystates[SDLK_SPACE]) {
            shoot(g);
        }
        
        // UFO
        if (ms_time() - lastufoupdate >= UFO_UPDATE) {
            lastufoupdate = ms_time();
            ufo(g);
        }
        
        // Alienposition aktualisieren?
        // Exponentialfunktion, die Level und Alienanzahl berücksichtigt
        if (ms_time() - lastenemyupdate >= ENEMY_UPDATE_BASE * pow(0.95, g->level * 3 + (ENEMY_COUNT - g->enemyContainer.aliveCount) / 4)) {
            lastenemyupdate = ms_time();
            updateBlocks(g);
            moveEnemys(g);
            alienShot(g);
        }
        
        // Schüsse aktualisieren
        if (ms_time() - lastshotupdate >= SHOT_UPDATE) {
            lastshotupdate = ms_time();
            updateShots(g);
            checkCollision(g);
            movePlayer(g, None);
        }
        
        usleep(20000); // begrenzt CPU Last
        // Nächster Grafikzustand
        SDL_Flip(g->screen);
    }
    
    SDL_Quit();
    return 0;
}
Beispiel #9
0
int main(int argc, char **argv)
{
	char *configfilename = "/etc/mpc2x.conf";
	config = config_file(configfilename);
	
	bool quit = false;

	// Init SDL
	SDL_Init(SDL_INIT_JOYSTICK | SDL_INIT_VIDEO | SDL_INIT_TIMER);
	// Prepare screen for GP2X
	screen = SDL_SetVideoMode( WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_DEPTH, SDL_SWSURFACE);
	if(!screen) {
		printf("SDL_SetVideoMode screen not initialised: %s\n",SDL_GetError());
		shutdown();
	}
	// Set window title, which we don't need on gp2x
	SDL_WM_SetCaption(WINDOW_TITLE, 0 );
	// Disable mouse cursus
	SDL_ShowCursor(SDL_DISABLE);

	// initialise the font stuff
	TTF_Init();

	// load the ttf font to be used
	char *fontpath = (char*) malloc(100);
	strcpy(fontpath,config->skin_path); // assume the font is in the skin path, should do this other way!
	strcat(fontpath,config->font_path);
	font = TTF_OpenFont(fontpath, 16);
	free(fontpath);
	// Initialize the joystick
	SDL_JoystickOpen(0);

	songname = "........Not connected or no song playing at the moment...........";
	scrollpos = 0;
	mpdConnect();
	buildGUI();
	updateGUI();
	
	#define SONGTITLEINTERVAL 10
	int interval = 0;

	while (!quit)
	{
		SDL_Delay(100);
		interval++;
		if (interval == SONGTITLEINTERVAL) {
			mpdGetSongTitle();
			interval = 0;
			}

		updateGUI();
		
		SDL_Event event;
		while( SDL_PollEvent( &event ) )
		{
			switch( event.type )
			{
				case SDL_JOYBUTTONUP:
					drawText(screen, "[ |< ]", 20, 200, 255, 255, 255);
					drawText(screen, "[>/||]", 80, 200, 255, 255, 255);
					drawText(screen, "[ >| ]", 140, 200, 255, 255, 255);
					SDL_Flip(screen);
					break;
				case SDL_JOYBUTTONDOWN:
					switch( event.jbutton.button )
					{
						case GP2X_BUTTON_VOLUP :
						// volume up
							mpd_sendSetvolCommand(conn, status->volume + 5);
							mpd_finishCommand(conn);
							break;
						case GP2X_BUTTON_VOLDOWN :
						// volume down
							mpd_sendSetvolCommand(conn, status->volume - 5);
							mpd_finishCommand(conn);
							break;
						case GP2X_BUTTON_A :
						// play/pause
							if(status->state == MPD_STATUS_STATE_PLAY)
							{
								mpd_sendPauseCommand(conn,1);
							}
							else if(status->state == MPD_STATUS_STATE_PAUSE || status->state == MPD_STATUS_STATE_STOP)
							{
								mpd_sendPauseCommand(conn,0);
							}
							mpd_finishCommand(conn);
							drawText(screen, "[>/||]", 80, 200, 255, 255, 0);
							SDL_Flip(screen);
							break;
						case GP2X_BUTTON_R :
						// next track
							mpd_sendNextCommand(conn);
							mpd_finishCommand(conn);
							drawText(screen, "[ >| ]", 140, 200, 255, 255, 0);
							SDL_Flip(screen);
							break;
						case GP2X_BUTTON_L :
						// prev track
							mpd_sendPrevCommand(conn);
							mpd_finishCommand(conn);
							drawText(screen, "[ |< ]", 20, 200, 255, 255, 0);
							SDL_Flip(screen);
							break;
						case GP2X_BUTTON_Y :
						// shuffle toggle
							if(status->random == 0)
							{
								mpd_sendRandomCommand(conn,1);
							}
							else
							{
								mpd_sendRandomCommand(conn,0);
							}
							mpd_finishCommand(conn);
							break;
						case GP2X_BUTTON_B :
						// repeat toggle
							if(status->repeat == 0)
							{
								mpd_sendRepeatCommand(conn,1);
							}
							else
							{
								mpd_sendRepeatCommand(conn,0);
							}
							mpd_finishCommand(conn);
							break;
						case GP2X_BUTTON_START :
						// quit
						 	quit=true;
							break;
						case GP2X_BUTTON_SELECT :
						// cycle other screens
							break;
						case GP2X_BUTTON_RIGHT :
						// forward in song
							mpd_sendSeekCommand(conn, status->song, status->elapsedTime + 5);
							mpd_finishCommand(conn);
							break;
						case GP2X_BUTTON_LEFT :
						// backward in song
							mpd_sendSeekCommand(conn, status->song, status->elapsedTime - 5);
							mpd_finishCommand(conn);
							break;
						default:
							break;
					}
					break;
				case SDL_KEYDOWN:
					switch( event.key.keysym.sym )
					{
						case SDLK_KP_PLUS :
						// volume up
							mpd_sendSetvolCommand(conn, status->volume + 5);
							mpd_finishCommand(conn);
							break;
						case SDLK_KP_MINUS :
						// volume down
							mpd_sendSetvolCommand(conn, status->volume - 5);
							mpd_finishCommand(conn);
							break;
						case SDLK_SPACE :
						// play/pause
							if(status->state == MPD_STATUS_STATE_PLAY)
							{
								mpd_sendPauseCommand(conn,1);
							}
							else if(status->state == MPD_STATUS_STATE_PAUSE || status->state == MPD_STATUS_STATE_STOP)
							{
								mpd_sendPauseCommand(conn,0);
							}
							mpd_finishCommand(conn);
							drawText(screen, "[>/||]", 80, 200, 255, 255, 0);
							SDL_Flip(screen);
							break;
						case SDLK_RIGHT	:
						// next track
							mpd_sendNextCommand(conn);
							mpd_finishCommand(conn);
							drawText(screen, "[ >| ]", 140, 200, 255, 255, 0);
							SDL_Flip(screen);
							break;
						case SDLK_LEFT :
						// prev track
							mpd_sendPrevCommand(conn);
							mpd_finishCommand(conn);
							drawText(screen, "[ |< ]", 20, 200, 255, 255, 0);
							SDL_Flip(screen);
							break;
						case SDLK_s :
						// shuffle toggle
							if(status->random == 0)
							{
								mpd_sendRandomCommand(conn,1);
							}
							else
							{
								mpd_sendRandomCommand(conn,0);
							}
							mpd_finishCommand(conn);
							break;
						case SDLK_r :
						// repeat toggle
							if(status->repeat == 0)
							{
								mpd_sendRepeatCommand(conn,1);
							}
							else
							{
								mpd_sendRepeatCommand(conn,0);
							}
							mpd_finishCommand(conn);
							break;
						case SDLK_ESCAPE :
						// quit
						 	quit=true;
							break;
						case SDLK_TAB :
						// cycle other screens
							break;
						case SDLK_UP :
						// forward in song
							mpd_sendSeekCommand(conn, status->song, status->elapsedTime + 5);
							mpd_finishCommand(conn);
							break;
						case SDLK_DOWN :
						// backward in song
							mpd_sendSeekCommand(conn, status->song, status->elapsedTime - 5);
							mpd_finishCommand(conn);
							break;
						default:
							break;
					}
					break;
			}
		}
	}

	shutdown();
	return 0;
}
Beispiel #10
0
//main loop functions
int initialize()
{
	/*	Setando coisas	*/

    quit = false;

    //Initialize all SDL subsystems
    if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
	{
		cout << "Problemas ao inicializar sistemas e subsistemas do SDL" << endl;    
		return -1;
	}

    //Initialize SDL_ttf 
    if( TTF_Init() == -1 ) 
	    return false;


	//The attributes of the screen
	const int SCREEN_WIDTH = 1980;
	const int SCREEN_HEIGHT = 1024 ;
	const int SCREEN_BPP = 32;

    //Set up the screen
    screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );

    //If there was an error in setting up the screen
    if( screen == NULL )
    {
		cout << "Problemas inicializando o video" << endl;
        return -2;
    }

    //Set the window caption
    SDL_WM_SetCaption( "The World Last War", NULL );	

	//objetos principais
	ImageHandlerSDLObj = new ImageHandlerSDL();
	drawObj = new Draw();
	randomObj = new Random();
	timer = new Timer();
	audioHandler = new AudioHandler();
	fontHandler = new FontHandler();

    //Load the images
	logoEmpresa = (*ImageHandlerSDLObj).load_image("images/gamaSoft.jpg",0);
  logoJogo = (*ImageHandlerSDLObj).load_image("images/logo.png",0);
	logoRecursos = (*ImageHandlerSDLObj).load_image("images/recursosTecnologicos.png",0);
	civilizationUnits = (*ImageHandlerSDLObj).load_image("images/unidades2.png",0);
	classificacaoIndicativa = (*ImageHandlerSDLObj).load_image("images/classificacaoIndicativa.png",0);	
	menu = (*ImageHandlerSDLObj).load_image("images/menu.png",0);
	mapa = (*ImageHandlerSDLObj).load_image("images/gamasoft_mapaTeste.png",0);
	escolhaNacao = (*ImageHandlerSDLObj).load_image("images/telaNacao.png", 0);
	nivel = (*ImageHandlerSDLObj).load_image("images/telaNivel.png", 0);
  telaInstrucoes = (*ImageHandlerSDLObj).load_image("images/telaInstrucoes.png", 0);
  telaOpcoes = (*ImageHandlerSDLObj).load_image("images/telaOpcoes.png", 0);
  telaCreditos = (*ImageHandlerSDLObj).load_image("images/telaCreditos.png", 0);
  telaLoading = (*ImageHandlerSDLObj).load_image("images/telaLoading.png", 0);
  loading = (*ImageHandlerSDLObj).load_image("images/loadingPiece.png", 0);
    

	(*audioHandler).initialize();
	(*fontHandler).initialize();

	//depois colocar no quadro 1 (0) da fase 1 apos a abertura no switch
	initializeCenario1();

	(*timer).start();

	return 1;	//sucess
}
Beispiel #11
0
int main( int argc, char* args[] ) {
    if (SDL_Init(SDL_INIT_VIDEO) !=0)
    {
        std::cerr << "SDL_Init failed\n";
        exit(EXIT_FAILURE);
    }
    if (TTF_Init() != 0) {
        std::cerr << "TTF_Init failed\n";
        exit(EXIT_FAILURE);
    }
    const SDL_VideoInfo* videoInfo = SDL_GetVideoInfo();
    int systemX = videoInfo->current_w;
    int systemY = videoInfo->current_h;
    Uint8 bpp = videoInfo->vfmt->BitsPerPixel;
    screen = SDL_SetVideoMode(systemX, systemY, bpp, SDL_SWSURFACE); // SDL_HWSURFACE | SDL_DOUBLEBUF
    if (!screen)
    {
        std::cerr << "SDL_SetVideoMode failed\n";
        exit(EXIT_FAILURE);
    }

    SDL_Rect r1_1 = {0,0,100,100};
    SDL_FillRect(screen, &r1_1, SDL_MapRGB(screen->format, 255,0,0));
    SDL_Rect r1_2 = {100,0,100,100};
    SDL_FillRect(screen, &r1_2, SDL_MapRGB(screen->format, 0,255,0));
    SDL_Rect r1_3 = {200,0,100,100};
    SDL_FillRect(screen, &r1_3, SDL_MapRGB(screen->format, 0,0,255));
    
    SDL_Rect r2_1 = {0,100,100,100};
    SDL_FillRect(screen, &r2_1, SDL_MapRGB(screen->format, 0,255,0));
    SDL_Rect r2_2 = {100,100,100,100};
    SDL_FillRect(screen, &r2_2, SDL_MapRGB(screen->format, 0,0,255));
    SDL_Rect r2_3 = {200,100,100,100};
    SDL_FillRect(screen, &r2_3, SDL_MapRGB(screen->format, 255,0,0));
    
    SDL_Rect r3_1 = {0,200,100,100};
    SDL_FillRect(screen, &r3_1, SDL_MapRGB(screen->format, 0,0,255));
    SDL_Rect r3_2 = {100,200,100,100};
    SDL_FillRect(screen, &r3_2, SDL_MapRGB(screen->format, 255,0,0));
    SDL_Rect r3_3 = {200,200,100,100};
    SDL_FillRect(screen, &r3_3, SDL_MapRGB(screen->format, 0,255,0));
    
    font = TTF_OpenFont("fonts/verdana.ttf",72);
    if(!font){
        std::cerr << "TTF_OpenFont failed\n";
        exit(EXIT_FAILURE);
    }
    message = TTF_RenderUTF8_Blended(font,"Hello!",textColor);
    if(!message){
        std::cerr << "TTF_Render failed\n";
        exit(EXIT_FAILURE);
    }
    messageRect.x = (systemX / 2) - (message->w / 2);
    messageRect.y = (systemY / 2) - (message->h / 2);
    SDL_BlitSurface(message, NULL, screen, &messageRect);
    
    SDL_Surface* loaded = IMG_Load("logo.png");
    if(!loaded){
        std::cerr << "IMG_Load failed\n";
        exit(EXIT_FAILURE);
    }
    image = SDL_DisplayFormatAlpha(loaded);
    SDL_FreeSurface(loaded);
    SDL_BlitSurface(image, NULL, screen, NULL);

    SDL_Flip(screen);
    
    SDL_Event event;
    bool quit = false;
    while(!quit) {
        SDL_WaitEvent(&event);
        switch (event.type) {
            case SDL_QUIT : quit = true; break;
            case SDL_KEYDOWN: {
                printf("The %s key was pressed!\n", SDL_GetKeyName(event.key.keysym.sym));
                switch( event.key.keysym.sym ) {
                    case SDLK_ESCAPE :  quit = true; break;
                    default : break;
                }
            }
            default : break;
        }
    }
    
    //SDL_Delay(10000);
    
    TTF_CloseFont(font);
    TTF_Quit();
    SDL_FreeSurface(message);
    SDL_FreeSurface(image);
    SDL_FreeSurface(screen);
    SDL_Quit();

    return EXIT_SUCCESS;
}
Beispiel #12
0
/**
 * \fn int gestionTextBox(int value, SDL_Surface *ecran, SDL_Rect zone, int limite)
 * \brief gère les interaction avec lutilisateur pour la modifiation et laffichage d'un nombre
 *
 * \param value La valeur initiale
 * \param ecran La surface sur laquelle on veut l'afficher
 * \param zone L'endroit où on veut afficher le nombre
 * \param limite Valeur maximum que peut prendre le nombre
 * \return la nouvelle valeur
 */
int gestionTextBox(int value, SDL_Surface *ecran, SDL_Rect zone, int limite){
    /**Déclaration des variables*/
    SDL_Color white = {255,255,255};
    SDL_Color black = {0,0,0};
    SDL_Surface *texte, *popup;
    char valide = 0;
    char affichageNb[3] = "";

    TTF_Init(); //Démarrage de SDL_ttf
    TTF_Font *police = TTF_OpenFont("Fonts/OCRAStd.otf", 16); //Charger la police
    SDL_Event event;


    do{
        /**Affichage de la valeur modifié*/
        sprintf(affichageNb, "%d",value); //convertion int -> string
        texte = TTF_RenderText_Blended(police, affichageNb, black);
        popup = SDL_CreateRGBSurface(SDL_HWSURFACE, texte->w, texte->h, 32, 0,0,0,0); //maj taille popup
        SDL_FillRect(popup, NULL, SDL_MapRGB(popup->format, 255, 255, 255)); //couleur de fond de la fenetre
        apply_surface(0, 0, texte, popup, NULL);
        apply_surface(zone.x, zone.y,popup, ecran, NULL);
        SDL_Flip(ecran); // Mise à jour de l'écran

        /**Modification de la valeur*/
        SDL_WaitEvent(&event);
        if(event.type == SDL_KEYDOWN){
            switch (event.key.keysym.sym){
                case SDLK_KP0:
                    value = value*10 + 0;
                    break;
                case SDLK_KP1:
                    value = value*10 + 1;
                    break;
                case SDLK_KP2:
                    value = value*10 + 2;
                    break;
                case SDLK_KP3:
                    value = value*10 + 3;
                    break;
                case SDLK_KP4:
                    value = value*10 + 4;
                    break;
                case SDLK_KP5:
                    value = value*10 + 5;
                    break;
                case SDLK_KP6:
                    value = value*10 + 6;
                    break;
                case SDLK_KP7:
                    value = value*10 + 7;
                    break;
                case SDLK_KP8:
                    value = value*10 + 8;
                    break;
                case SDLK_KP9:
                    value = value*10 + 9;
                    break;
                case SDLK_BACKSPACE:
                    value = (value - value%10) / 10;
                    break;
                case SDLK_KP_ENTER: //validation
                    valide = 1;
                    break;
                case SDLK_RETURN: //validation
                    valide = 1;
                    break;
                default:
                    break;
            }
            if (value>limite){
                value = limite;
            }else if(value/1000>0){//limite laffichage a 3 chiffre
                value = (value - value%10) / 10;
            }
        }

        /**Masquage de l'ancienne valeur*/
        SDL_FillRect(popup, NULL, SDL_MapRGB(popup->format, 0, 0, 0)); //couleur de fond de la fenetre
        apply_surface(zone.x, zone.y,popup, ecran, NULL);
    }while(valide == 0);

    sprintf(affichageNb, "%d",value); //ajout du char score
    texte = TTF_RenderText_Blended(police, affichageNb, white);
    apply_surface(0, 0, texte, popup, NULL);
    apply_surface(zone.x, zone.y,popup, ecran, NULL);
    SDL_Flip(ecran); // Mise à jour de l'écran

    TTF_CloseFont(police); //Fermer la police
    SDL_FreeSurface(texte); // On libère la surface
    SDL_FreeSurface(popup); // On libère la surface
    TTF_Quit(); //Arrêt de SDL_ttf

    return value;//renvoie la nouvelle valeur
}
Beispiel #13
0
/**
 * \fn SDL_Rect* afficherMenuOption(SDL_Surface *ecran, Option *opt, int joueurSelect)
 * \brief affiche un menu avec les options rejouer, quitter et option
 *
 * \param optAffichage Les options d'affichage
 * \param opt Les options de jeu
 * \param joueurSelect Le numero du joueur selectionné pour la modification de sont apparence
 * \return un tableau de SDL_Rect, chaque case contient les position et taille d'un des boutons
 */
SDL_Rect* afficherMenuOption(SDL_Surface *ecran, Option *opt, int joueurSelect){//add: choix nb case libre, mode de jeu
    /**Déclaration des variables*/
    SDL_Surface *texte;
    int popWidth = ecran->w, popHeight = ecran->h, marge = 32/4;
    SDL_Color white = {255,255,255};

    /**Zone menu*/
    SDL_Surface *popup = SDL_CreateRGBSurface(SDL_HWSURFACE, popWidth, popHeight, 32, 0, 0, 0, 0);
    rectangle(0,0,popup->w, popup->h, white, popup); //contour de la surface
    apply_surface(0, 0,popup, ecran, NULL);

    TTF_Init(); //Démarrage de SDL_ttf
    TTF_Font *police;

    /**Titre*/
    police = TTF_OpenFont("Fonts/OCRAStd.otf", 20); //Charger la police
    texte = TTF_RenderText_Blended(police, "Option", white);
    apply_surface(16, 16, texte, ecran, NULL);

    police = TTF_OpenFont("Fonts/OCRAStd.otf", 16); //Charger la police

    /**Zone nombre de joueurs*/
    int firstMarge = 16 + texte->w + marge;
    int positionX = firstMarge;
    int positionY = 16+texte->h +4* marge;
    char affichageNb[21+3+1] = "Nombre de joueurs: ";
    texte = TTF_RenderText_Blended(police, affichageNb, white);
    apply_surface(positionX, positionY, texte, ecran, NULL);
    positionX +=texte->w+marge;
    sprintf(affichageNb, "%d",opt->nbJoueur);
    texte = TTF_RenderText_Blended(police, affichageNb, white);
    apply_surface(positionX, positionY, texte, ecran, NULL);
    //position du bouton
    boutons[6].x = positionX;
    boutons[6].y = positionY;
    boutons[6].w = texte->w;
    boutons[6].h = texte->h;

    /**Zone apparence du joueur*/
    positionX = firstMarge;
    positionY += texte->h + 2*marge;
    texte = TTF_RenderText_Blended(police, "Apparence du joueur: ", white);
    apply_surface(positionX, positionY, texte, ecran, NULL);
    //btn player
    if (opt->nbJoueur>1){
        int i=0;
        boutons = realloc(boutons, (7 + opt->nbJoueur) * sizeof(SDL_Rect));//reallocation
        for (i=0; i<opt->nbJoueur; i++){
            positionX +=texte->w+marge;
            sprintf(affichageNb, "J%d",i+1); //ajout du char score
            texte = TTF_RenderText_Blended(police, affichageNb, white);
            apply_surface(positionX, positionY, texte, ecran, NULL);
            //position du bouton
            boutons[i+7].x = positionX;
            boutons[i+7].y = positionY;
            boutons[i+7].w = texte->w;
            boutons[i+7].h = texte->h;
            //affichage du joueur selectionné
            if (joueurSelect == i){
                rectangle(boutons[i+7].x,boutons[i+7].y,boutons[i+7].w, boutons[i+7].h, white, ecran); //contour de la case
            }
        }
    }
    //image charset
    positionX = firstMarge;
    positionY += texte->h + 2*marge;
    SDL_Surface *charset =  IMG_Load(araignee.pathName); //load le charset
    apply_surface(positionX, positionY, charset, ecran, &araignee.clip);
    //position du bouton
    boutons[0].x = positionX;
    boutons[0].y = positionY;
    boutons[0].w = charset->w/16;
    boutons[0].h = charset->h/16;
    //image charset
    positionX += araignee.clip.w+marge;
    charset =  IMG_Load(squelette.pathName); //load le charset
    apply_surface(positionX, positionY, charset, ecran, &squelette.clip);
    //position du bouton
    boutons[1].x = positionX;
    boutons[1].y = positionY;
    boutons[1].w = charset->w/16;
    boutons[1].h = charset->h/16;
    //image charset
    positionX += squelette.clip.w+marge;
    charset =  IMG_Load(farmer.pathName); //load le charset
    apply_surface(positionX, positionY, charset, ecran, &farmer.clip);
    //position du bouton
    boutons[2].x = positionX;
    boutons[2].y = positionY;
    boutons[2].w = charset->w/farmer.nbImageAnim;
    boutons[2].h = charset->h/4;

    //affichage de l'apparence selectionné
    if (opt->sprites[joueurSelect] == &araignee){
        rectangle(boutons[0].x,boutons[0].y,boutons[0].w, boutons[0].h, white, ecran); //contour de la case
    }else if (opt->sprites[joueurSelect] == &squelette){
        rectangle(boutons[1].x,boutons[1].y,boutons[1].w, boutons[1].h, white, ecran); //contour de la case
    }else if (opt->sprites[joueurSelect] == &farmer){
        rectangle(boutons[2].x,boutons[2].y,boutons[2].w, boutons[2].h, white, ecran); //contour de la case
    }

    /**Zone nombre de ressources*/
    positionX = firstMarge;
    positionY += charset->h/4 + 2*marge;
    sprintf(affichageNb, "Nombre de ressources: ");
    texte = TTF_RenderText_Blended(police, affichageNb, white);
    apply_surface(positionX, positionY, texte, ecran, NULL);
    positionX +=texte->w+marge;
    sprintf(affichageNb, "%d",opt->nbRessource); //ajout du char score
    texte = TTF_RenderText_Blended(police, affichageNb, white);
    apply_surface(positionX, positionY, texte, ecran, NULL);
    //position du bouton
    boutons[3].x = positionX;
    boutons[3].y = positionY;
    boutons[3].w = texte->w;
    boutons[3].h = texte->h;

    /**Zone taille de la map*/
    positionX = firstMarge;
    positionY += texte->h + 2*marge;
    texte = TTF_RenderText_Blended(police, "Taille de la map X: ", white);
    apply_surface(positionX, positionY, texte, ecran, NULL);
    positionX +=texte->w+marge;
    sprintf(affichageNb, "%d", opt->nbCaseX); //ajout du char score
    texte = TTF_RenderText_Blended(police, affichageNb, white);
    apply_surface(positionX, positionY, texte, ecran, NULL);
    //position du bouton
    boutons[4].x = positionX;
    boutons[4].y = positionY;
    boutons[4].w = texte->w;
    boutons[4].h = texte->h;
    positionX +=texte->w+marge;
    sprintf(affichageNb, "Y: ");//3+2
    texte = TTF_RenderText_Blended(police, affichageNb, white);
    apply_surface(positionX, positionY, texte, ecran, NULL);
    positionX +=texte->w+marge;
    sprintf(affichageNb, "%d",opt->nbCaseY); //ajout du char score
    texte = TTF_RenderText_Blended(police, affichageNb, white);
    apply_surface(positionX, positionY, texte, ecran, NULL);
    //position du bouton
    boutons[5].x = positionX;
    boutons[5].y = positionY;
    boutons[5].w = texte->w;
    boutons[5].h = texte->h;


    TTF_CloseFont(police); //Fermer la police
    SDL_FreeSurface(texte); // On libère la surface
    SDL_FreeSurface(popup); // On libère la surface
    TTF_Quit(); //Arrêt de SDL_ttf

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

    return boutons;
}
Beispiel #14
0
void GW_PlatformSDL::initialize()
{
    if (!initialized_)
    {
        GWDBG_OUTPUT("SDL: Initialize");

        // initialize SDL video
        if ( SDL_Init( sdlinit(SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_TIMER) ) < 0 )
            throw GW_Exception(string("Unable to init SDL: "+string(SDL_GetError())));

#ifndef GW_NO_SDL_MIXER
        if ( Mix_OpenAudio(22050, AUDIO_S16SYS, 1, audiobufsize_get()) < 0)
            throw GW_Exception(string("Unable to init SDL_mixer: "+string(Mix_GetError())));
#endif

#ifndef GW_NO_SDL_TTF
        if ( TTF_Init() < 0 )
            throw GW_Exception(string("Unable to init SDL_ttf: "+string(TTF_GetError())));
#endif

#ifndef GW_NO_SDL_MIXER
        Mix_AllocateChannels(6);
        sound_volume(75);
#endif

        custom_initialize();

        // make sure SDL cleans up before exit
        atexit(SDL_Quit);

        // set application icon
        plat_init();

        // create a new window
        window_ = SDL_CreateWindow("Game & Watch simulator - by Hitnrun / ZsoltK & Madrigal",
                                   SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
                                   width_, height_,
                                   fullscreen_ ?  SDL_WINDOW_FULLSCREEN_DESKTOP : SDL_WINDOW_SHOWN);
        if ( !window_ )
            throw GW_Exception(string("Unable to allocate game window: " + string(SDL_GetError())));

        renderer_ = SDL_CreateRenderer(window_, -1, SDL_RENDERER_ACCELERATED);
        if ( !renderer_ )
            throw GW_Exception(string("Unable to allocate renderer: " + string(SDL_GetError())));


        // Let SDL & GPU do the scaling
        SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear");
        SDL_RenderSetLogicalSize(renderer_, width_, height_);

        SDL_ShowCursor(SDL_DISABLE);

#ifndef GW_NO_SDL_TTF
        // load font
        //font_=TTF_OpenFont( bf::path( bf::path(platformdata_get() ) / "andalemo.ttf" ).string().c_str(), fontsize_get() );
        string pfont(platformdata_get() + "/" + "andalemo.ttf" );
        font_=TTF_OpenFont( pfont.c_str(), fontsize_get() );
        if (!font_)
            throw GW_Exception(string("Unable to load font: "+string(TTF_GetError())));
#endif

        initialized_=true;
    }
}
void Inventaire(sJoueur *Perso,sMESS_ITEMS *items_data)
{

TTF_Init();
SDL_Rect postexte;
SDL_Surface *texte =NULL;
TTF_Font *police= NULL;
police = TTF_OpenFont("carolingia.ttf" ,50);
SDL_Color noire = {135,65,14};

int tabEquipement[10]={0,0,0,0,0,0,0,0,0,0};

SDL_Rect position,positionFenetreListe,positionFenetreSelect,positionOnglets,positionImagesOnglets,posrefreshEquipement;

//Affichage ecran
SDL_Init(SDL_INIT_VIDEO);
SDL_Surface* ecran = NULL;
ecran=SDL_SetVideoMode(1680,1050,32,SDL_HWSURFACE/*|SDL_FULLSCREEN*/);
SDL_FillRect(ecran,NULL,SDL_MapRGB(ecran->format,0,0,0));

//Affichage interface
SDL_Surface* interface =NULL;
interface= SDL_LoadBMP("Sprites/II/Interface II.bmp");
SDL_SetColorKey(interface, SDL_SRCCOLORKEY, SDL_MapRGB(interface->format, 0, 0, 255));
position.x=0;
position.y=0;

//Affichage Fenetres Liste
SDL_Surface* fenetreListe = NULL;
fenetreListe = SDL_LoadBMP("Sprites/II/Liste II.bmp");
positionFenetreListe.x=113;
positionFenetreListe.y=189;

//Affichage Fenetres Select
SDL_Surface* fenetreSelect = NULL;
fenetreSelect = SDL_LoadBMP("Sprites/II/Fenetre Select II.bmp");
SDL_SetColorKey(fenetreSelect, SDL_SRCCOLORKEY, SDL_MapRGB(fenetreSelect->format, 0, 0, 255));
positionFenetreSelect.x=113;
positionFenetreSelect.y=0;

//Affichage Onglets
SDL_Surface* Onglets = NULL;
Onglets = SDL_LoadBMP("Sprites/II/Onglets II.bmp");
SDL_SetColorKey(Onglets, SDL_SRCCOLORKEY, SDL_MapRGB(Onglets->format, 0, 0, 255));
positionOnglets.x=722;

//Affichage Onglets
SDL_Surface* ImagesOnglets = NULL;
ImagesOnglets = SDL_LoadBMP("Sprites/II/Images Onglets II.bmp");
SDL_SetColorKey(ImagesOnglets, SDL_SRCCOLORKEY, SDL_MapRGB(ImagesOnglets->format, 0, 0, 255));
positionImagesOnglets.x=724;
positionImagesOnglets.y=162;

//Affichage Refresh Equipement
SDL_Surface* refreshEquipement = NULL;
refreshEquipement = SDL_LoadBMP("Sprites/II/Refersh Equipement II.bmp");
SDL_SetColorKey(refreshEquipement, SDL_SRCCOLORKEY, SDL_MapRGB(refreshEquipement->format, 0, 0, 255));
posrefreshEquipement.x=724;
posrefreshEquipement.y=162;

int tabObjet[10];
int deplaList=0;
int listType=1;

SDL_BlitSurface(interface,NULL,ecran,&position);
positionOnglets.y=156;
SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
positionOnglets.y=287;
SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
positionOnglets.y=419;
SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
positionOnglets.y=550;
SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
positionOnglets.y=682;
SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);

SDL_BlitSurface(ImagesOnglets,NULL,ecran,&positionImagesOnglets);


affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);

SDL_Flip(ecran);

int Select=0;


//EVENT
 int continuer = 1;

    SDL_Event event;

    while (continuer)
        {
            SDL_WaitEvent(&event);
            switch(event.type)
                {
                    case SDL_KEYDOWN:

                    switch (event.key.keysym.sym)
                        {
                            case SDLK_ESCAPE:
                            continuer=0;
                            break;

                            default:
                                break;

                        }
                    break;

                case SDL_MOUSEBUTTONDOWN:

//SELECTION
                if (event.button.x>=112 && event.button.y>=188 && event.button.x<=676 && event.button.y<=255)
                    {
                        Select =0;

                        positionFenetreSelect.y=189;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);

                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }
                if (event.button.x>=112 && event.button.y>=256 && event.button.x<=676 && event.button.y<=325)
                    {
                        Select =1;

                        positionFenetreSelect.y=256;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }
                if (event.button.x>=112 && event.button.y>=326 && event.button.x<=676 && event.button.y<=391)
                    {
                        Select=2;

                        positionFenetreSelect.y=324;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }
                if (event.button.x>=112 && event.button.y>=391 && event.button.x<=676 && event.button.y<=460)
                    {
                        Select =3;

                        positionFenetreSelect.y=389;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }
                if (event.button.x>=112 && event.button.y>=461 && event.button.x<=676 && event.button.y<=525)
                    {
                        Select =4;

                        positionFenetreSelect.y=457;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }
                if (event.button.x>=112 && event.button.y>=526 && event.button.x<=676 && event.button.y<=592)
                    {
                        Select =5;

                        positionFenetreSelect.y=524;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }
                if (event.button.x>=112 && event.button.y>593 && event.button.x<=676 && event.button.y<=660)
                    {
                        Select =6;

                        positionFenetreSelect.y=590;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }
                if (event.button.x>=112 && event.button.y>=661 && event.button.x<=676 && event.button.y<=725)
                    {
                        Select =7;

                        positionFenetreSelect.y=658;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }
                if (event.button.x>=112 && event.button.y>=725 && event.button.x<=676 && event.button.y<=792)
                    {
                        Select =8;

                        positionFenetreSelect.y=722;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }
                if (event.button.x>=112 && event.button.y>=793 && event.button.x<=676 && event.button.y<=959)
                    {
                        Select =9;

                        positionFenetreSelect.y=791;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }

//FLECHES
                if (event.button.x>=9 && event.button.y>=532 && event.button.x<=100 && event.button.y<=700)
                    {

                            deplaList++;
                                                    affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                            SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                            SDL_Flip(ecran);

                    }
                if (event.button.x>=9 && event.button.y>=361 && event.button.x<=100 && event.button.y<=531)
                    {
                        if (deplaList>0)
                            {
                        deplaList--;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                            }
                    }

//ONGLETS
                if (event.button.x>=722 && event.button.y>=170 && event.button.x<=810 && event.button.y<=305)
                    {
                    deplaList=0;
                    listType=1;
                                            affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                    positionOnglets.y=682;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=550;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=419;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=287;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=156;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    SDL_BlitSurface(ImagesOnglets,NULL,ecran,&positionImagesOnglets);
                    SDL_Flip(ecran);
                    }
                if (event.button.x>=722 && event.button.y>=306 && event.button.x<=810 && event.button.y<=436)
                    {
                    deplaList=0;
                    listType=2;
                                            affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                    positionOnglets.y=682;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=550;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=419;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=156;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=287;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    SDL_BlitSurface(ImagesOnglets,NULL,ecran,&positionImagesOnglets);
                    SDL_Flip(ecran);
                    }
                if (event.button.x>=722 && event.button.y>=437 && event.button.x<=810 && event.button.y<=567)
                    {
                    deplaList=0;
                    listType=3;
                                            affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                    positionOnglets.y=682;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=550;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=156;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=287;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=419;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    SDL_BlitSurface(ImagesOnglets,NULL,ecran,&positionImagesOnglets);
                    SDL_Flip(ecran);
                    }
                if (event.button.x>=722 && event.button.y>=568 && event.button.x<=810 && event.button.y<=698)
                    {
                    deplaList=0;
                    listType=4;
                    affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                    positionOnglets.y=682;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=156;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=287;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=419;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=550;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    SDL_BlitSurface(ImagesOnglets,NULL,ecran,&positionImagesOnglets);
                    SDL_Flip(ecran);
                    }
                if (event.button.x>=722 && event.button.y>=699 && event.button.x<=810 && event.button.y<=829)
                    {
                    deplaList=0;
                    listType=5;
                                            affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);

                    positionOnglets.y=156;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=287;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=419;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=550;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    positionOnglets.y=682;
                    SDL_BlitSurface(Onglets,NULL,ecran,&positionOnglets);
                    SDL_BlitSurface(ImagesOnglets,NULL,ecran,&positionImagesOnglets);
                    SDL_Flip(ecran);
                    }

//EQUIPER
                if (event.button.x>=1215 && event.button.y>=859 && event.button.x<=1614 && event.button.y<=1011 && Select==0)
                    {
                        items_data->data[tabObjet[Select]].equipe=1;
                        items_data->data[tabEquipement[items_data->data[tabObjet[Select]].categorie]]=items_data->data[tabObjet[Select]];
                        affEquip(Perso,tabEquipement,ecran,refreshEquipement,texte,postexte,posrefreshEquipement,police,noire,items_data);

                    }
                if (event.button.x>=1215 && event.button.y>=859 && event.button.x<=1614 && event.button.y<=1011 && Select==1)
                    {
                        items_data->data[tabObjet[Select]].equipe=1;
                        items_data->data[tabEquipement[items_data->data[tabObjet[Select]].categorie]]=items_data->data[tabObjet[Select]];
                        affEquip(Perso,tabEquipement,ecran,refreshEquipement,texte,postexte,posrefreshEquipement,police,noire,items_data);

                    }
                if (event.button.x>=1215 && event.button.y>=859 && event.button.x<=1614 && event.button.y<=1011 && Select==2)
                    {
                        items_data->data[tabObjet[Select]].equipe=1;
                        items_data->data[tabEquipement[items_data->data[tabObjet[Select]].categorie]]=items_data->data[tabObjet[Select]];
                        affEquip(Perso,tabEquipement,ecran,refreshEquipement,texte,postexte,posrefreshEquipement,police,noire,items_data);

                    }
                if (event.button.x>=1215 && event.button.y>=859 && event.button.x<=1614 && event.button.y<=1011 && Select==3)
                    {
                        items_data->data[tabObjet[Select]].equipe=1;
                        items_data->data[tabEquipement[items_data->data[tabObjet[Select]].categorie]]=items_data->data[tabObjet[Select]];
                        affEquip(Perso,tabEquipement,ecran,refreshEquipement,texte,postexte,posrefreshEquipement,police,noire,items_data);

                    }
                if (event.button.x>=1215 && event.button.y>=859 && event.button.x<=1614 && event.button.y<=1011 && Select==4)
                    {
                        items_data->data[tabObjet[Select]].equipe=1;
                        items_data->data[tabEquipement[items_data->data[tabObjet[Select]].categorie]]=items_data->data[tabObjet[Select]];
                        affEquip(Perso,tabEquipement,ecran,refreshEquipement,texte,postexte,posrefreshEquipement,police,noire,items_data);

                    }
                if (event.button.x>=1215 && event.button.y>=859 && event.button.x<=1614 && event.button.y<=1011 && Select==5)
                    {
                        items_data->data[tabObjet[Select]].equipe=1;
                        items_data->data[tabEquipement[items_data->data[tabObjet[Select]].categorie]]=items_data->data[tabObjet[Select]];
                        affEquip(Perso,tabEquipement,ecran,refreshEquipement,texte,postexte,posrefreshEquipement,police,noire,items_data);

                    }
                if (event.button.x>=1215 && event.button.y>=859 && event.button.x<=1614 && event.button.y<=1011 && Select==6)
                    {
                        items_data->data[tabObjet[Select]].equipe=1;
                        items_data->data[tabEquipement[items_data->data[tabObjet[Select]].categorie]]=items_data->data[tabObjet[Select]];
                        affEquip(Perso,tabEquipement,ecran,refreshEquipement,texte,postexte,posrefreshEquipement,police,noire,items_data);

                    }
                if (event.button.x>=1215 && event.button.y>=859 && event.button.x<=1614 && event.button.y<=1011 && Select==7)
                    {
                        items_data->data[tabObjet[Select]].equipe=1;
                        items_data->data[tabEquipement[items_data->data[tabObjet[Select]].categorie]]=items_data->data[tabObjet[Select]];
                        affEquip(Perso,tabEquipement,ecran,refreshEquipement,texte,postexte,posrefreshEquipement,police,noire,items_data);
                    }
                if (event.button.x>=1215 && event.button.y>=859 && event.button.x<=1614 && event.button.y<=1011 && Select==8)
                    {
                        items_data->data[tabObjet[Select]].equipe=1;
                        items_data->data[tabEquipement[items_data->data[tabObjet[Select]].categorie]]=items_data->data[tabObjet[Select]];
                        affEquip(Perso,tabEquipement,ecran,refreshEquipement,texte,postexte,posrefreshEquipement,police,noire,items_data);

                    }
                if (event.button.x>=1215 && event.button.y>=859 && event.button.x<=1614 && event.button.y<=1011 && Select==9)
                    {
                        items_data->data[tabObjet[Select]].equipe=1;
                        items_data->data[tabEquipement[items_data->data[tabObjet[Select]].categorie]]=items_data->data[tabObjet[Select]];
                        affEquip(Perso,tabEquipement,ecran,refreshEquipement,texte,postexte,posrefreshEquipement,police,noire,items_data);
                    }

//JETER
                if (event.button.x>=672 && event.button.y>=900 && event.button.x<=986 && event.button.y<=1050 && Select==0 && items_data->data[tabObjet[Select]].equipe==0)
                    {

                                items_data->data[tabObjet[Select]].possede=0;
                                items_data->data[tabObjet[Select]].equipe=0;

                                                        affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                                SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                                affEquip(Perso,tabEquipement,ecran,refreshEquipement,texte,postexte,posrefreshEquipement,police,noire,items_data);
                                SDL_Flip(ecran);
                    }
                if (event.button.x>=672 && event.button.y>=900 && event.button.x<=986 && event.button.y<=1050 && Select==1 && items_data->data[tabObjet[Select]].equipe==0)
                    {
                        items_data->data[tabObjet[Select]].possede=0;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                        affEquip(Perso,tabEquipement,ecran,refreshEquipement,texte,postexte,posrefreshEquipement,police,noire,items_data);

                    }
                if (event.button.x>=672 && event.button.y>=900 && event.button.x<=986 && event.button.y<=1050 && Select==2 && items_data->data[tabObjet[Select]].equipe==0)
                    {

                        items_data->data[tabObjet[Select]].possede=0;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                        affEquip(Perso,tabEquipement,ecran,refreshEquipement,texte,postexte,posrefreshEquipement,police,noire,items_data);

                    }
                if (event.button.x>=672 && event.button.y>=900 && event.button.x<=986 && event.button.y<=1050 && Select==3 && items_data->data[tabObjet[Select]].equipe==0)
                    {
                        items_data->data[tabObjet[Select]].possede=0;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }
                if (event.button.x>=672 && event.button.y>=900 && event.button.x<=986 && event.button.y<=1050 && Select==4 && items_data->data[tabObjet[Select]].equipe==0)
                    {
                        items_data->data[tabObjet[Select]].possede=0;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }
                if (event.button.x>=672 && event.button.y>=900 && event.button.x<=986 && event.button.y<=1050 && Select==5 && items_data->data[tabObjet[Select]].equipe==0)
                    {
                        items_data->data[tabObjet[Select]].possede=0;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }
                if (event.button.x>=672 && event.button.y>=900 && event.button.x<=986 && event.button.y<=1050 && Select==6 && items_data->data[tabObjet[Select]].equipe==0)
                    {
                        items_data->data[tabObjet[Select]].possede=0;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }
                if (event.button.x>=672 && event.button.y>=900 && event.button.x<=986 && event.button.y<=1050 && Select==7 && items_data->data[tabObjet[Select]].equipe==0)
                    {
                        items_data->data[tabObjet[Select]].possede=0;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);                        SDL_Flip(ecran);
                    }
                if (event.button.x>=672 && event.button.y>=900 && event.button.x<=986 && event.button.y<=1050 && Select==8 && items_data->data[tabObjet[Select]].equipe==0)
                    {
                        items_data->data[tabObjet[Select]].possede=0;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }
                if (event.button.x>=672 && event.button.y>=900 && event.button.x<=986 && event.button.y<=1050 && Select==9 && items_data->data[tabObjet[Select]].equipe==0)
                    {
                        items_data->data[tabObjet[Select]].possede=0;
                                                affListeInventaire(tabObjet, deplaList ,listType,fenetreListe, ecran, texte, positionFenetreListe, postexte, items_data, police, noire);
                        SDL_BlitSurface(fenetreSelect,NULL,ecran,&positionFenetreSelect);
                        SDL_Flip(ecran);
                    }



                break;
            break;
                }

    }




}
Beispiel #16
0
// initialize application display variables 
bool SDLApp::init()
{
    bool success = true;
    
    //Initialize SDL
    if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
    {
        printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
        success = false;
    }
    else
    {
        //Set texture filtering to linear
        if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
        {
            printf( "Warning: Linear texture filtering not enabled!" );
            success = false;
        }
        
        //Create window
        window = SDL_CreateWindow( "GemsArr", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
        
        if( window == NULL )
        {
            printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
            success = false;
        }
        else
        {
            //Create renderer for window
            renderer = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED );
            if( renderer == NULL )
            {
                printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
                success = false;
            }
            else
            {
                //Initialize renderer color
                SDL_SetRenderDrawColor( renderer, 0xFF, 0xFF, 0xFF, 0xFF );
                
                //Initialize PNG loading
                int imgFlags = IMG_INIT_PNG;
                if( !( IMG_Init( imgFlags ) & imgFlags ) )
                {
                    printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
                    success = false;
                }
                
                //Initialize SDL_mixer
                if( Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0 )
                {
                    printf( "SDL_mixer could not initialize! SDL_mixer Error: %s\n", Mix_GetError() );
                    success = false;
                }
                
                //Initialize SDL_ttf
                if( TTF_Init() == -1 )
                {
                    printf( "SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError() );
                    success = false;
                }
            }
            
            game = new Game();
            
            // fetches media from respective folders
            game->fetchMedia();
            
            // loads all the media required
            game->loadMedia( renderer );
            
            // prints board
            cout << game->stringGrid();
            
            // prints available moves
            cout << game->stringMoveList( game->moveList() );
            
            return true;
        }
    }
    
    return success;
}
Beispiel #17
0
int main( int argc, char** argv )
{
  // Variables definition
  int wiimote_paired = 0;
  int x = -1;
  int y = -1;
  int batt = 0;
  char big_msg[256];
  char small_msg[256];
  unsigned char rumble = 0;
  unsigned char rpt_mode = 0;
  SDL_Surface* screen = NULL;
  SDL_Event event;
  SDL_Rect big_position, small_position;
  SDL_Surface* big_text = NULL;
  SDL_Surface* small_text = NULL;
  TTF_Font* big_font = NULL;
  TTF_Font* small_font = NULL;
  AppState appstate = PAIRING;
  cwiid_wiimote_t* wiimote;
  bdaddr_t bdaddr = *BDADDR_ANY;
  struct cwiid_state state;
  SDL_Color white = {0,0,0};
  SDL_Rect dot;

  // Variables initialisation
  big_position.x = 180;
  big_position.y = 250;
  small_position.x = 300;
  small_position.y = 50;

  // SDL and SDL_TTF initialization
  if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_TIMER ) )
    {
      fprintf( stderr, "Error while initializing SDL: %s\n", SDL_GetError() );
      exit( EXIT_FAILURE );
    }
  if( TTF_Init() )
    {
     fprintf( stderr, "Error while initializing SDL_TTF: %s\n", TTF_GetError() );
     exit( EXIT_FAILURE );
    }

  // Resources loading
  big_font = TTF_OpenFont( "gratis.ttf", 35 );
  if( big_font == NULL )
    {
      fprintf( stderr, "Error while loading font: %s\n", TTF_GetError() );
      exit( EXIT_FAILURE );
    }
  small_font = TTF_OpenFont( "gratis.ttf", 15 );
  if( small_font == NULL )
    {
      fprintf( stderr, "Error while loading font: %s\n", TTF_GetError() );
      exit( EXIT_FAILURE );
    }

  // Main window creation
  screen = SDL_SetVideoMode( S_WIDTH, S_HEIGHT, S_BPP, S_FLAGS );
  SDL_WM_SetCaption( "Wiimote pointer display", NULL );

  // Pair with the wiimote and rumble to notify
  printf( "Trying to pair with the wiimote now.\nPut the wiimote in search mode (press 1+2) ...\n" );
  if( wiimote = cwiid_open( &bdaddr, 0 ) )
    {
      wiimote_paired = 1;
      appstate = DISPLAY;
      toggle_bit( rumble, 0x01 );
      cwiid_set_rumble( wiimote, rumble );
      usleep( 300000 );
      toggle_bit( rumble, 0x01 );
      cwiid_set_rumble( wiimote, rumble );
      // toggle IR reporting ON
      toggle_bit( rpt_mode, 0x08 );
      cwiid_set_rpt_mode( wiimote, rpt_mode );
    }

  // Main loop
  while( appstate != EXIT )
    {
      // Take care of events if there is any
      if( SDL_PollEvent( &event ) )
	{
	  switch( event.type )
	    {
	    case SDL_QUIT:
	      appstate = EXIT;
	      break;
	    
	    case SDL_KEYDOWN:
	      if( event.key.keysym.sym == SDLK_ESCAPE )
		appstate = EXIT;
	      break;
		 
	    }
	}

      // Query the wiimote
      if( appstate == DISPLAY )
	{
	  cwiid_get_state( wiimote, &state );
	  if( state.ir_src[0].valid )
	    {
	      SDL_FillRect( screen, NULL, SDL_MapRGB( screen->format, 0, 255, 0 ) );
	      x = state.ir_src[0].pos[0];
	      y = state.ir_src[0].pos[1];
	    }
	  else
	    {
	      SDL_FillRect( screen, NULL, SDL_MapRGB( screen->format, 255, 0, 0 ) );
	    }
	  batt = (int)(100.0 * state.battery / 0xD0);
	  //	  sprintf( big_msg, "IR source position: (%d,%d)", x, y );
	  dot.x = (int) (x * S_WIDTH) / X_MAX;
	  dot.y = (int) (y * S_HEIGHT) / Y_MAX;
	  dot.w = 10;
	  dot.h = 10;
	  SDL_FillRect( screen, &dot, SDL_MapRGB( screen->format, 255, 255, 255) );
	  sprintf( small_msg, "Battery remaining: %d%%", batt );
	  //big_text = TTF_RenderText_Solid( big_font, big_msg, white );
	  small_text = TTF_RenderText_Solid( small_font, small_msg, white );
	  //SDL_BlitSurface( big_text, NULL, screen, &big_position );
	  SDL_BlitSurface( small_text, NULL, screen, &small_position );
	}

      // Render the screen
      SDL_Flip( screen );
    }

  // Free resources and exits sub-systems
  TTF_CloseFont( big_font );
  TTF_CloseFont( small_font );
  TTF_Quit();
  if( wiimote_paired )
    cwiid_close( wiimote );
  else
    fprintf( stderr, "No wiimotes could be found\n" );
  SDL_Quit();
  
  return EXIT_SUCCESS;
}
Beispiel #18
0
/**
* \fn int loadInterface(sInterface *p_interface)
* \brief Fonction d'initialisation de structure de type sInterface
*
* \param *p_interface pointeur vers une structure de type sInterface
* \return int représentant le déroulement de la fonction
*/
int loadInterface(sInterface *p_interface) {
	int l_i;
	char l_casePath[50] = "./assets/sprite/case_01.png", l_persoPath[50] = "./assets/sprite/perso_0.png";

	SDL_Surface *l_sprite;
	SDL_Rect l_posAnim, l_offset;

	if (SDL_Init(SDL_INIT_EVERYTHING)) {
		fprintf(stdout, "[SDL] Initialization Error (%s)\n", SDL_GetError());
		return EXIT_FAILURE;
	}
	IMG_Init(IMG_INIT_PNG);
	TTF_Init();

	p_interface->window = SDL_CreateWindow("-RACCOON ZANOS-", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN );
	if (!(p_interface->window)) {
		fprintf(stderr, "[SDL] Window creation error (%s)\n", SDL_GetError());
		return EXIT_FAILURE;
	}
	SDL_ShowCursor(SDL_DISABLE);

	p_interface->renderer = SDL_CreateRenderer(p_interface->window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE);

	for (l_i = 0; l_i < CASE_TYPE_AMOUNT; ++l_i) {
		l_casePath[21] = (int)(l_i / 10) + 48; 
		l_casePath[22] = (l_i - (int)(l_i / 10)*10) + 48;
		l_sprite = IMG_Load(l_casePath);
		p_interface->caseSprite[l_i] = SDL_CreateTextureFromSurface(p_interface->renderer, l_sprite);
		SDL_FreeSurface(l_sprite);
	}

	for (l_i = 0; l_i < 4; ++l_i) {
		l_persoPath[22] = l_i + 48;
		l_sprite = IMG_Load(l_persoPath);
		p_interface->player.playerSprite[l_i] = SDL_CreateTextureFromSurface(p_interface->renderer, l_sprite);
		SDL_FreeSurface(l_sprite);
	}

	p_interface->effect.particle = NULL;
	l_sprite = IMG_Load("./assets/sprite/particle_0.png");
	p_interface->effect.particleSprite[0] = SDL_CreateTextureFromSurface(p_interface->renderer, l_sprite);
	l_sprite = IMG_Load("./assets/sprite/particle_1.png");
	p_interface->effect.particleSprite[1] = SDL_CreateTextureFromSurface(p_interface->renderer, l_sprite);
	l_sprite = IMG_Load("./assets/sprite/particle_2.png");
	p_interface->effect.particleSprite[2] = SDL_CreateTextureFromSurface(p_interface->renderer, l_sprite);
	SDL_FreeSurface(l_sprite);

	l_sprite = IMG_Load("./assets/sprite/cursor.png");
	p_interface->cursor = SDL_CreateTextureFromSurface(p_interface->renderer, l_sprite);
	SDL_FreeSurface(l_sprite);

	l_posAnim.x = 0;
	l_posAnim.y = 0;
	l_posAnim.h = WINDOW_HEIGHT;
	l_posAnim.w = WINDOW_WIDTH;
	loadAnimation(0, &(p_interface->effect.l_mountain), 159, l_posAnim, "./assets/sprite/anim/mountain_", p_interface, 3);
	loadAnimation(1, &(p_interface->effect.l_tuto), 8, l_posAnim, "./assets/sprite/anim/tuto_", p_interface, 1);
	loadAnimation(1, &(p_interface->effect.l_congrate), 4, l_posAnim, "./assets/sprite/anim/congratulation_", p_interface, 1);

	l_posAnim.h = 250;
	l_posAnim.w = 250;
	l_posAnim.x = WINDOW_HEIGHT - l_posAnim.h;
	l_posAnim.y = WINDOW_WIDTH - l_posAnim.w;
	l_offset.x = 1000;
	l_offset.y = 1000;
	l_offset.w = -1;
	l_offset.h = -1;
	loadAnimation(1, &(p_interface->effect.l_raccoon), 3, l_posAnim, "./assets/sprite/anim/raccoon-skate_", p_interface, 10);

	l_posAnim.h = 400;
	l_posAnim.w = 400;
	l_offset.x = 10;
	l_offset.y = 10;
	l_offset.w = 0;
	l_offset.h = -1;
	centrerPosition(&l_posAnim, l_offset);
	loadAnimation(1, &(p_interface->effect.l_logo), 2, l_posAnim, "./assets/sprite/anim/raccoonzanos_", p_interface, 100);

	l_posAnim.w = 200;
	l_posAnim.h = 100;
	l_offset.x = 10;
	l_offset.y = 10;
	l_offset.w = 0;
	l_offset.h = 0;
	centrerPosition(&l_posAnim, l_offset);
	loadAnimation(1, &(p_interface->effect.l_play), 4, l_posAnim, "./assets/sprite/anim/play_", p_interface, 5);

	p_interface->backgroundSprite = SDL_CreateTexture(p_interface->renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_TARGET, WINDOW_WIDTH, WINDOW_HEIGHT);


	p_interface->player.isSliding = FALSE;
	p_interface->player.direction = DUP;
	p_interface->compteur = 0;

	p_interface->solution = NULL;

	loadSonor(&(p_interface->sonor));

	SDL_SetRenderDrawColor(p_interface->renderer, 255, 0, 0, 255);
	SDL_RenderClear(p_interface->renderer);

	return 0;
}
Beispiel #19
0
int main(int argc, char *argv[])
{
	atexit(SDL_Quit);
	srand(time(NULL));

	if(SDL_Init(SDL_INIT_EVERYTHING) == 1){
		std::cerr << "Error initializing SDL\n";
		return -1;
	}

	SDL_WM_SetCaption("SDL Puyo Puyo", NULL);

	SDL_Surface *screen = SDL_SetVideoMode(SCR_W, SCR_H, SCR_BPP, SDL_SWSURFACE );
	if(screen == NULL){
		std::cerr << "Error in SetVideoMode\n";
		return -1;
	}

	SDL_Event event;
	Uint32 last_tick = SDL_GetTicks();

	/* Holy f*****g sound initialization batman. */
	int mix_flags = MIX_INIT_MP3;
	int init_mix = Mix_Init(mix_flags);
	int audio_rate = 22050;
	Uint16 audio_format = AUDIO_S16; /* 16-bit stereo */
	int audio_channels = 2;
	int audio_buffers = 4096;

	if(Mix_OpenAudio(audio_rate, audio_format, audio_channels, audio_buffers)) {
	  std::cerr << "Unable to open audio\n";
	  mixer_on = false;
	} else {		
		if(mix_flags & init_mix != mix_flags){
			std::cerr << "Failed to init mp3 support, bg music disabled :(\n";
			std::cerr << "mixer error: " << Mix_GetError() << std::endl;
			mixer_on = false;
		} else{
			mixer_on = true;
		}
	}

	/* Init TTF */
	if(TTF_Init() == -1){
		std::cerr << "Could not initialize TTF subsystem :(\n";
		font_on = false;
	} 
	else {
		font_on = true;
	}

	GameState *gs = InitNewGame();
	if(gs == NULL){
		std::cerr << "Error initializing new game.\n";
		return -1;
	}

	gameloop:
	while(gs->playing)
	{
		while(SDL_PollEvent(&event))
		{
			if(event.type == SDL_QUIT)
				return 0;
			if(event.type == SDL_KEYDOWN)
			{
				if(event.key.keysym.sym == SDLK_ESCAPE)
					return 0;

				HandleInput(gs, event);
			}
		}

		if(SDL_GetTicks() - last_tick > 1000/60){
			UpdateTick(gs);
			last_tick = SDL_GetTicks();
		}

		RenderTick(screen, gs);
		SDL_Flip(screen);
	}

	RenderTick(screen, gs);
	SDL_Delay(5000);

	CleanGameState(gs);
	gs = InitNewGame();
	goto gameloop;
	

	if(screen)
		SDL_FreeSurface(screen);

	TTF_Quit();
	Mix_Quit();
	return 0;
}
Beispiel #20
0
int main() {
    int fin=0, touche, action;
    Partie partie;
    Dalek *daleks = NULL;
    Doc doc;
    Surfaces surfce;
    
    /*Initialisations*/
    SDL_Init(SDL_INIT_VIDEO);
    TTF_Init();
    srand(time(NULL));
    #ifdef PSP
    pspDebugScreenInit();
    SetupCallbacks();
    #endif
    
    /*Initialisation de l'ecran principal*/
    surfce.screen = SDL_SetVideoMode(SCREEN_W, SCREEN_H, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
    #ifndef PSP /*Titre si pas sur le PSP*/
        SDL_WM_SetCaption("Daleks-SDL", NULL);
    #endif
    
    /*Affichage de l'intro, sert de loading Screen*/
    afficherIntro(surfce.screen);
    
    /*Creation de la partie*/
    partie = nouvellePartie();
    
    /*Initialisation des personnages*/
    initNiveau(partie, &doc, &daleks);
    
    /*Initialisation des surfaces SDL*/
    if (initialiserSurfaces(&surfce) != 0) {
        exit(EXIT_FAILURE);
    }
    
    /*Le loading est fini, on attend une touche de l'utilisateur*/
    while (lireTouche() == -1) {
    }
    
    /*Sert a annuler la touche enfoncee precedement*/
    afficherPartie(partie, surfce, doc, daleks);
    
    while (!fin) {
        /**********
            ETAPES
            1. Lire la touche
            2. Effectuer l'action
            3. Bouger les daleks
            4. Verifier les morts
            5. Verifier l'etat de la partie
            6. Afficher le jeu
          **********/
        action = 1; /*Pour savoir si il y a eu une action ce tour*/
        touche = lireTouche();
        switch (touche) {
            case KEY_UP:
                if (moveDoc(0, -1, &doc, daleks, partie) != 0) {
                    action = 0;
                }
                break;
            case KEY_DOWN:
                if (moveDoc(0, 1, &doc, daleks, partie) != 0) {
                    action = 0;
                }
                break;
            case KEY_LEFT:
                if (moveDoc(-1, 0, &doc, daleks, partie) != 0) {
                    action = 0;
                }
                break;
            case KEY_RIGHT:
                if (moveDoc(1, 0, &doc, daleks, partie) != 0) {
                    action = 0;
                }
                break;
            case KEY_UP_LEFT:
                if (moveDoc(-1, -1, &doc, daleks, partie) != 0) {
                    action = 0;
                }
                break;
            case KEY_UP_RIGHT:
                if (moveDoc(1, -1, &doc, daleks, partie) != 0) {
                    action = 0;
                }
                break;
            case KEY_DOWN_LEFT:
                if (moveDoc(-1, 1, &doc, daleks, partie) != 0) {
                    action = 0;
                }
                break;
            case KEY_DOWN_RIGHT:
                if (moveDoc(1, 1, &doc, daleks, partie) != 0) {
                    action = 0;
                }
                break;
            case KEY_STAY:
                if (moveDoc(0, 0, &doc, daleks, partie) != 0) {
                    action = 0;
                }
                break;
            case KEY_ZAP:
                if (zapper(doc, daleks, &partie) != 0) {
                    action = 0;
                }
                break;
            case KEY_TELEPORT:
                teleportDoc(&doc, daleks, partie);
                break;
            case KEY_RUN:
                run(&doc, daleks, &partie, surfce);
                action = 0; /*Les daleks ont deja bouge*/
                break;
            case KEY_QUIT:
                fin = 1;
            default: /*aucune action*/
                action = 0;
        }
        
        /*Les daleks bougent seulement si le doc a fait une action*/
        if (action) {
            moveDaleks(daleks, doc, partie);
            checkMorts(&doc, daleks, &partie);
        }
        
        if (getStatutPartie(doc, daleks, partie) == 1) {
            afficherPartie(partie, surfce, doc, daleks); /*Affichage de la partie avant d'afficher lvlUp*/
            afficherLevelUp(surfce.screen);                 /*Parce que l'affichage est long*/
            monterNiveau(&partie);
            initNiveau(partie, &doc, &daleks);
        } else if (getStatutPartie(doc, daleks, partie) == 2) {
            afficherPartie(partie, surfce, doc, daleks); /*Affichage de la partie avant d'afficher la mort*/
            afficherDead(surfce.screen);                    /*Parce que l'affichage est long*/
            reset(&partie);
            initNiveau(partie, &doc, &daleks);
        }
        
        afficherPartie(partie, surfce, doc, daleks);
    }
    
    libererSurfaces(surfce);
    TTF_Quit();
    SDL_Quit();
    
    #ifdef PSP
        sceKernelExitGame();
    #endif
    return 0;
}
Beispiel #21
0
void ui_init() {
    // Init SDL
    if(SDL_Init(SDL_INIT_VIDEO) < 0) FAIL("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);

    ww = config.ui.window_width;
    wh = config.ui.window_height;

    window = SDL_CreateWindow("Radiance", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, ww, wh, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN);
    if(window == NULL) FAIL("Window could not be created: %s\n", SDL_GetError());
    context = SDL_GL_CreateContext(window);
    if(context == NULL) FAIL("OpenGL context could not be created: %s\n", SDL_GetError());
    if(SDL_GL_SetSwapInterval(1) < 0) fprintf(stderr, "Warning: Unable to set VSync: %s\n", SDL_GetError());
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    if(renderer == NULL) FAIL("Could not create renderer: %s\n", SDL_GetError());
    if(TTF_Init() < 0) FAIL("Could not initialize font library: %s\n", TTF_GetError());

    // Init OpenGL
    GLenum e;
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glClearColor(0, 0, 0, 0);
    if((e = glGetError()) != GL_NO_ERROR) FAIL("OpenGL error: %s\n", gluErrorString(e));

    // Make framebuffers
    glGenFramebuffersEXT(1, &select_fb);
    glGenFramebuffersEXT(1, &pat_fb);
    glGenFramebuffersEXT(1, &crossfader_fb);
    glGenFramebuffersEXT(1, &pat_entry_fb);
    glGenFramebuffersEXT(1, &spectrum_fb);
    glGenFramebuffersEXT(1, &waveform_fb);
    glGenFramebuffersEXT(1, &strip_fb);
    if((e = glGetError()) != GL_NO_ERROR) FAIL("OpenGL error: %s\n", gluErrorString(e));

    // Init select texture
    glGenTextures(1, &select_tex);
    glBindTexture(GL_TEXTURE_2D, select_tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ww, wh, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    glBindTexture(GL_TEXTURE_2D, 0);

    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, select_fb);
    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, select_tex, 0);

    // Init pattern textures
    pattern_textures = calloc(config.ui.n_patterns, sizeof(GLuint));
    if(pattern_textures == NULL) MEMFAIL();
    pattern_name_textures = calloc(config.ui.n_patterns, sizeof(SDL_Texture *));
    pattern_name_width = calloc(config.ui.n_patterns, sizeof(int));
    pattern_name_height = calloc(config.ui.n_patterns, sizeof(int));
    if(pattern_name_textures == NULL || pattern_name_width == NULL || pattern_name_height == NULL) MEMFAIL();
    glGenTextures(config.ui.n_patterns, pattern_textures);
    if((e = glGetError()) != GL_NO_ERROR) FAIL("OpenGL error: %s\n", gluErrorString(e));
    for(int i = 0; i < config.ui.n_patterns; i++) {
        glBindTexture(GL_TEXTURE_2D, pattern_textures[i]);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, config.ui.pattern_width, config.ui.pattern_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    }

    // Init crossfader texture
    glGenTextures(1, &crossfader_texture);
    glBindTexture(GL_TEXTURE_2D, crossfader_texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, config.ui.crossfader_width, config.ui.crossfader_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, crossfader_fb);
    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, crossfader_texture, 0);

    // Init pattern entry texture
    glGenTextures(1, &pat_entry_texture);
    glBindTexture(GL_TEXTURE_2D, pat_entry_texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, config.ui.pat_entry_width, config.ui.pat_entry_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, pat_entry_fb);
    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, pat_entry_texture, 0);

    // Spectrum data texture
    glGenTextures(1, &tex_spectrum_data);
    glBindTexture(GL_TEXTURE_1D, tex_spectrum_data);
    glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage1D(GL_TEXTURE_1D, 0, GL_R32F, config.audio.spectrum_bins, 0, GL_RED, GL_FLOAT, NULL);

    // Spectrum UI element
    glGenTextures(1, &spectrum_texture);
    glBindTexture(GL_TEXTURE_2D, spectrum_texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, config.ui.spectrum_width, config.ui.spectrum_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, spectrum_fb);
    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, spectrum_texture, 0);

    // Waveform data texture
    glGenTextures(1, &tex_waveform_data);
    glBindTexture(GL_TEXTURE_1D, tex_waveform_data);
    glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA32F, config.audio.waveform_length, 0, GL_RGBA, GL_FLOAT, NULL);

    glGenTextures(1, &tex_waveform_beats_data);
    glBindTexture(GL_TEXTURE_1D, tex_waveform_beats_data);
    glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA32F, config.audio.waveform_length, 0, GL_RGBA, GL_FLOAT, NULL);

    // Waveform UI element
    glGenTextures(1, &waveform_texture);
    glBindTexture(GL_TEXTURE_2D, waveform_texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, config.ui.waveform_width, config.ui.waveform_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, waveform_fb);
    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, waveform_texture, 0);

    // Strip indicators
    glGenTextures(1, &strip_texture);
    glBindTexture(GL_TEXTURE_2D, strip_texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, config.pattern.master_width, config.pattern.master_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, strip_fb);
    glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, strip_texture, 0);

    // Done allocating textures & FBOs, unbind and check for errors
    glBindTexture(GL_TEXTURE_2D, 0);
    glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
    if((e = glGetError()) != GL_NO_ERROR) FAIL("OpenGL error: %s\n", gluErrorString(e));

    if((blit_shader = load_shader("resources/blit.glsl")) == 0) FAIL("Could not load blit shader!\n%s", load_shader_error);
    if((main_shader = load_shader("resources/ui_main.glsl")) == 0) FAIL("Could not load UI main shader!\n%s", load_shader_error);
    if((pat_shader = load_shader("resources/ui_pat.glsl")) == 0) FAIL("Could not load UI pattern shader!\n%s", load_shader_error);
    if((crossfader_shader = load_shader("resources/ui_crossfader.glsl")) == 0) FAIL("Could not load UI crossfader shader!\n%s", load_shader_error);
    if((text_shader = load_shader("resources/ui_text.glsl")) == 0) FAIL("Could not load UI text shader!\n%s", load_shader_error);
    if((spectrum_shader = load_shader("resources/ui_spectrum.glsl")) == 0) FAIL("Could not load UI spectrum shader!\n%s", load_shader_error);
    if((waveform_shader = load_shader("resources/ui_waveform.glsl")) == 0) FAIL("Could not load UI waveform shader!\n%s", load_shader_error);
    if((strip_shader = load_shader("resources/strip.glsl")) == 0) FAIL("Could not load strip indicator shader!\n%s", load_shader_error);

    // Stop text input
    SDL_StopTextInput();

    // Open the font
    font = TTF_OpenFont(config.ui.font, config.ui.fontsize);
    if(font == NULL) FAIL("Could not open font %s: %s\n", config.ui.font, SDL_GetError());

    // Init statics
    pat_entry = false;

    SDL_Surface * surf;
    surf = TTF_RenderText_Blended(font, "wtf, why is this necessary", font_color);
    if(surf == NULL) FAIL("Could not create surface: %s\n", SDL_GetError());
    SDL_Texture *texture = SDL_CreateTextureFromSurface(renderer, surf);
    if(texture == NULL) FAIL("Could not create texture: %s\n", SDL_GetError());
    SDL_FreeSurface(surf);
    SDL_DestroyTexture(texture);
}
Beispiel #22
0
GM_Debug::GM_Debug()
{

	desktop.SetWidth(options.w);
	desktop.SetHeight(options.h);
	desktop.ResetTransformations();

	desktop.AddObject(&btnButton);
	btnButton.SetPos(100,100);
	btnButton.SetWidth(128);
	btnButton.SetHeight(16);
	btnButton.SetCaption("Button");
	btnButton.SetBGColor(.75,.75,.75,1);
	btnButton.SetOnClick(GM_Debug::ButtonOnClick);

	desktop.AddObject(&btnExit);
	btnExit.SetPos(100,116);
	btnExit.SetWidth(128);
	btnExit.SetHeight(16);
	btnExit.SetCaption("Exit");
	btnExit.SetBGColor(1,0,0,1);
	btnExit.SetOnClick(GM_Debug::ExitOnClick);

	desktop.AddObject(&txtSprite);
	txtSprite.SetPos(100,132);
	txtSprite.SetWidth(128);
	txtSprite.SetHeight(16);
	txtSprite.SetCaption("200");

	desktop.AddObject(&txtItem);
	txtItem.SetPos(100,148);
	txtItem.SetWidth(128);
	txtItem.SetHeight(16);
	txtItem.SetCaption("100");

	desktop.AddObject(&btnUpdate);
	btnUpdate.SetPos(100,164);
	btnUpdate.SetWidth(128);
	btnUpdate.SetHeight(16);
	btnUpdate.SetCaption("Update gfx");
	btnUpdate.SetBGColor(1,0,0,1);
	btnUpdate.SetOnClick(GM_Debug::UpdateOnClick);


    desktop.AddObject(&txtLocX);
    desktop.AddObject(&txtLocY);
    desktop.AddObject(&txtLocZ);
    txtLocX.SetWidth(50);
    txtLocY.SetWidth(50);
    txtLocZ.SetWidth(50);
    txtLocX.SetCaption("32600");
    txtLocY.SetCaption("31750");
    txtLocZ.SetCaption("7");
    txtLocX.SetHeight(16);
    txtLocY.SetHeight(16);
    txtLocZ.SetHeight(16);
    txtLocX.SetPos(50,190);
    txtLocY.SetPos(100,190);
    txtLocZ.SetPos(150,190);

    desktop.AddObject(&btnUpdateMap);
    btnUpdateMap.SetPos(200,190);
    btnUpdateMap.SetHeight(16);
    btnUpdateMap.SetWidth(120);
    btnUpdateMap.SetCaption("Update map");
    btnUpdateMap.SetOnClick(GM_Debug::UpdateMapOnClick);


    desktop.AddObject(grid.getGrid());
    grid.getGrid()->SetPos(0, 0);
    grid.setRows(3);
    grid.setItemSize(100,20);
    grid.setPadding(5,5);
    grid.addItem("Hello world", NULL, NULL);
    grid.addItem("Testing grid", NULL, NULL);
    grid.addItem("How about this", NULL, NULL);
    grid.addItem("This rox", NULL, NULL);
    grid.addItem("Sure?", NULL, NULL);
    grid.setOnClick(cb3);

#ifdef GMDEBUG_STACKPANEL_TEST
	desktop.AddObject(&yatcstackpanel);
    yatcstackpanel.SetPos(400,100);
    yatcstackpanel.SetHeight(200);
    yatcstackpanel.SetWidth(100);
    yatcstackpanel.SetBGActiveness(false);
    for (int i = 0; i < YSPWINDOWS; i++) {
        std::stringstream s;
        s << "yspwTest[" << i << "]";
        yspwTest[i].SetHeight(15);
        yspwTest[i].SetCaption(s.str().c_str());
        yatcstackpanel.AddObject(&yspwTest[i]);
    }
#endif

	
	
	
	
	
	outfit = new winOutfit_t;
	desktop.AddObject(&outfit->window);
	
	Outfit_t outfitcurr;
	
	std::list<AvailOutfit_t> olist;
	AvailOutfit_t avail;
	
	avail.name = "Citizen";
	outfitcurr.m_looktype =	avail.id		= 128;
	outfitcurr.m_addons	  =	avail.addons	= 0;
	outfitcurr.m_lookhead = 50;
	outfitcurr.m_lookbody = 60;
	outfitcurr.m_looklegs = 70;
	outfitcurr.m_lookfeet = 80;
	outfitcurr.m_lookitem = 0;
	olist.push_back(avail);
	avail.name = "Another One";
	avail.id = 129;
	avail.addons = 0;
	olist.push_back(avail);
	outfit->openSelf(outfitcurr,olist);
	
	
    popup = NULL;
    killpopup = false;
    map[0] = map[1] = map[2] = map[3] = NULL;
    mapcount = 0;
    mapw = 256;
    maph = 256;

	if(g_engine){
		background = g_engine->createSprite("Tibia.pic", 0);
		spr = g_engine->createSprite("Tibia.spr", 200);
		//thing = new ItemUI(6401, 1);
		thing = NULL;

		//background->addColor(.5, 1., 1.);
	}
	else{  // i think that if g_engine does not exist, we might as well crash. what do you think, guys? ivucica
		NativeGUIError("Somehow, engine managed to not initialize.", PRODUCTSHORT " Fatal Error");
		exit(1);
	}
	printf("2\n");

	#ifdef SDLTTF_EXPERIMENT
	{
	    int ptsize=11;
        char fontname[]="arial.ttf";

        TTF_Init();

        font = TTF_OpenFont(fontname,ptsize);
        if ( font == NULL ) {
            fprintf(stderr, "Couldn't load %d pt font from %s: %s\n",
                                    ptsize, fontname, SDL_GetError());

        }

        int renderstyle=0;
        renderstyle |= TTF_STYLE_BOLD;
        TTF_SetFontStyle(font, renderstyle);

	}
	#endif
}
Beispiel #23
0
/**
 * \fn guiPlay(BoardSize size)
 * \brief This function is the main game loop
 * \details Function that create a new game, perform the game loop and display the game with SDL
 * \param size Variable representing the size of the Board (Small, Medium or Large)
 */
int guiPlay(BoardSize size)
{
      /*******************/
     /**   VARIABLES   **/
    /*******************/

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

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

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

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


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

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

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

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

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

    guiSetFieldType(game, assets, size);


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

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


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

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

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

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

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


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

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


        }

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

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

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

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

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

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

    //TTF_Quit();
    //SDL_Quit();
    return idWinner;
}
Beispiel #24
0
/**
 * \brief      Main pour lancer le jeu
 * \details    Gestion des evenements (clavier) de l'utilisateur pour lancer le jeu
 */
int main(int argc, char *argv[])
{
    score=0;

    // Variables pour ecriture avec TTF
    TTF_Font *police, *police2, *police3 = NULL;
    SDL_Color couleurBlanche = {255, 255, 255};
    SDL_Color couleurScore = {0, 0, 0};
    SDL_Surface *texteP1, *texteP2, *texteP3, *texteScore, *texteScore2 = NULL;

    TTF_Init();

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

    /* Chargement des polices */
    police = TTF_OpenFont("ARCHRISTY.ttf", 65);
    police2 = TTF_OpenFont("ARCHRISTY.ttf", 35);
    police3 = TTF_OpenFont("ARCHRISTY.ttf", 26);
    /* Écriture du texte dans la SDL_Surface texte en mode Blended (optimal) */
    texteP1 = TTF_RenderText_Blended(police2, "HOW PLAY TO SQUIRREL ACORN : ", couleurBlanche);
    texteP2 = TTF_RenderText_Blended(police3, "PRESS 1 : NORMAL MODE", couleurBlanche);
    texteP3 = TTF_RenderText_Blended(police3, "PRESS 2 : NO CONSTRAINTS MODE (without obstacles)", couleurBlanche);
    // Init des positions des cases et du personnage
    initilisationPositions();

    SDL_Init(SDL_INIT_VIDEO);

    ecran = SDL_SetVideoMode(LARGEUR_FENETRE, HAUTEUR_FENETRE, TAILLE_SPRITE, SDL_HWSURFACE); // Ouverture de la fenêtre
    if (ecran == NULL)
    {
        fprintf(stderr, "Impossible de charger le mode video : %s\n", SDL_GetError());
        exit(EXIT_FAILURE);
    }

    SDL_WM_SetCaption("2D GAME | SQUIRREL ACORN", NULL);

    // Autres variables pour les positions des ecritures
    SDL_Rect positionT;
    SDL_Rect positionT2;
    SDL_Rect positionT3;
    SDL_Rect positionT4;
    SDL_Rect positionT5;
    SDL_Rect positionT6;
    SDL_Rect positionScore;
    SDL_Rect positionScore2;
    positionT.x = 70;
    positionT.y = 185;
    positionT2.x = 45;
    positionT2.y = 265;
    positionT3.x = 27;
    positionT3.y = 365;
    positionT4.x = 70;
    positionT4.y = 215;
    positionT5.x = 170;
    positionT5.y = 275;
    positionT6.x = 20;
    positionT6.y = 330;
    positionScore.x = 75;
    positionScore.y = 265;
    positionScore2.x = 150;
    positionScore2.y = 345;

    // Affichage du texte
    SDL_BlitSurface(texteP1, NULL, ecran, &positionT4); /* Blit du texte */
    SDL_BlitSurface(texteP2, NULL, ecran, &positionT5); /* Blit du texte */
    SDL_BlitSurface(texteP3, NULL, ecran, &positionT6); /* Blit du texte */

    // Initialisation du tableau avec la position des ressources
    int tabR[4];
    tabR[0]=14;
    tabR[1]=138;
    tabR[2]=242;
    tabR[3]=359;

    SDL_Flip(ecran);

    //Gestion des evèvements ( inputs )
    while (exec)
    {
        SDL_WaitEvent(&event);
        switch(event.type)
        {
            case SDL_QUIT:
                exec=false;
                break;
            case SDL_KEYDOWN:
                switch(event.key.keysym.sym)
                {
                case SDLK_UP:
                    versHaut();
                    break;
                case SDLK_DOWN:
                    versBas();
                    break;
                case SDLK_RIGHT:
                    versDroite();
                    break;
                case SDLK_LEFT:
                    versGauche();
                    break;
                case SDLK_1:
                    // Affichage de la carte ...
                    formationCarte();
                    // ... et des objets.
                    placementObjets(1);
                    SDL_BlitSurface(perso, &positionPerso, ecran, &posPerso);
                    SDL_Flip(ecran);
                    SDL_Delay(2000);
                    // Lancement de l'algo
                    score=dijkstra1(tabR,score);
                    if(score!=0){
                        // Affichage du score
                        char sc[13];
                        char sco[3];
                        strcat(sc,"You win ! Score : ");
                        sprintf(sco, "%d", score);
                        strcat(sc,sco);
                        /* Écriture du texte dans la SDL_Surface texte en mode Solid (rapide) */
                        texteScore = TTF_RenderText_Solid(police, sc, couleurScore);
                        SDL_BlitSurface(texteScore, NULL, ecran, &positionScore); /* Blit du texte */;
                        texteScore2 = TTF_RenderText_Solid(police2, "(PRESS ESCAPE TO QUIT)", couleurScore);
                        SDL_BlitSurface(texteScore2, NULL, ecran, &positionScore2); /* Blit du texte */;
                        SDL_Flip(ecran);}
                    break;
                case SDLK_KP1:
                    // Affichage de la carte ...
                    formationCarte();
                    // ... et des objets.
                    placementObjets(1);
                    SDL_BlitSurface(perso, &positionPerso, ecran, &posPerso);
                    SDL_Flip(ecran);
                    SDL_Delay(2000);
                    // Lancement de l'algo
                    score=dijkstra1(tabR,score);
                    if(score!=0){
                        // Affichage du score
                        char sc[13];
                        char sco[3];
                        strcat(sc,"You win ! Score : ");
                        sprintf(sco, "%d", score);
                        strcat(sc,sco);
                        /* Écriture du texte dans la SDL_Surface texte en mode Solid (rapide) */
                        texteScore = TTF_RenderText_Solid(police, sc, couleurScore);
                        SDL_BlitSurface(texteScore, NULL, ecran, &positionScore); /* Blit du texte */;
                        texteScore2 = TTF_RenderText_Solid(police2, "(PRESS ESCAPE TO QUIT)", couleurScore);
                        SDL_BlitSurface(texteScore2, NULL, ecran, &positionScore2); /* Blit du texte */;
                        SDL_Flip(ecran);}
                    break;
                case SDLK_2:
                    // Affichage de la carte ...
                    formationCarte();
                    // ... et des objets.
                    placementObjets(1);
                    SDL_BlitSurface(perso, &positionPerso, ecran, &posPerso);
                    SDL_Flip(ecran);
                    SDL_Delay(2000);
                    // Lancement de l'algo
                    score=dijkstra2(tabR,score);
                    if(score!=0){
                        // Affichage du score
                        char sc[13];
                        char sco[3];
                        strcat(sc,"You win ! Score : ");
                        sprintf(sco, "%d", score);
                        strcat(sc,sco);
                        /* Écriture du texte dans la SDL_Surface texte en mode Solid (rapide) */
                        texteScore = TTF_RenderText_Solid(police, sc, couleurScore);
                        SDL_BlitSurface(texteScore, NULL, ecran, &positionScore); /* Blit du texte */;
                        texteScore2 = TTF_RenderText_Solid(police2, "(PRESS ESCAPE TO QUIT)", couleurScore);
                        SDL_BlitSurface(texteScore2, NULL, ecran, &positionScore2); /* Blit du texte */;
                        SDL_Flip(ecran);}
                    break;
                case SDLK_KP2:
                    // Affichage de la carte ...
                    formationCarte();
                    // ... et des objets.
                    placementObjets(1);
                    SDL_BlitSurface(perso, &positionPerso, ecran, &posPerso);
                    SDL_Flip(ecran);
                    SDL_Delay(2000);
                    // Lancement de l'algo
                    score=dijkstra2(tabR,score);
                    if(score!=0){
                        // Affichage du score
                        char sc[13];
                        char sco[3];
                        strcat(sc,"You win ! Score : ");
                        sprintf(sco, "%d", score);
                        strcat(sc,sco);
                        /* Écriture du texte dans la SDL_Surface texte en mode Solid (rapide) */
                        texteScore = TTF_RenderText_Solid(police, sc, couleurScore);
                        SDL_BlitSurface(texteScore, NULL, ecran, &positionScore); /* Blit du texte */;
                        texteScore2 = TTF_RenderText_Solid(police2, "(PRESS ESCAPE TO QUIT)", couleurScore);
                        SDL_BlitSurface(texteScore2, NULL, ecran, &positionScore2); /* Blit du texte */;
                        SDL_Flip(ecran);}
                    break;
                    case SDLK_ESCAPE:
                        // Pour quitter le jeu
                        exit(0);
                    break;
            }
            break;
        }
    }

    // Liberation de la surface
    SDL_FreeSurface(sprites);

    TTF_CloseFont(police);
    TTF_Quit();

    SDL_Quit();


    return EXIT_SUCCESS; // Fermeture du programme
}
Beispiel #25
0
bool SDLWrapper::initialize(){
	bool successSDL = false;
	bool successIMG = false;
	bool successMixer = false;
	bool successTTF = false;

	SDL_version compiled;

	Log(DEBUG) << "Initializing systems...";

	// Initializing SDL_TTF.
	const int ttfInit = TTF_Init();
	if(ttfInit == 0){
		successTTF = true;

		SDL_TTF_VERSION(&compiled);
		SDLWrapper::logSDLVersion("SDL_TTF", compiled);
	}
	else{
		Log(ERROR) << "Could not initialize TTF." << TTF_GetError();
	}

	// Initializing SDL with initFlags.
	const Uint32 initFlags = SDL_INIT_EVERYTHING;
	const int sdlInit = SDL_Init(initFlags);

	if(sdlInit == 0){
		successSDL = true;

		SDL_version linked;
		SDL_VERSION(&compiled);
		SDL_GetVersion(&linked);

		SDLWrapper::logSDLVersion("SDL", compiled, SDL_GetRevision());
	}
	else{
		Log(ERROR) << "Could not initialize SDL." << SDL_GetError();
	}

	// Initializing SDL_image with imgFlags.
	const Uint32 imgFlags = IMG_INIT_PNG;
	if((IMG_Init(imgFlags) & imgFlags)){
		successIMG = true;

		SDL_IMAGE_VERSION(&compiled);
		SDLWrapper::logSDLVersion("SDL_image", compiled);
	}
	else{
		Log(ERROR) << "Could not initialize SDL_Image." << IMG_GetError();
	}

	// Initializing SDL_mixer.
	const int frequency = 44100;
	const int channels = 2;
	const int chunksize = 4096;
	const int initialized = Mix_OpenAudio(frequency, MIX_DEFAULT_FORMAT, channels, chunksize);
	if(initialized == 0){
		successMixer = true;

		SDL_MIXER_VERSION(&compiled);
		SDLWrapper::logSDLVersion("SDL_mixer", compiled);
	}
	else{
		Log(ERROR) << "Could not initialize SDL_Mixer" << Mix_GetError();
	}

	// If even one system fails to initialize, returns false.
	return (successSDL && successIMG && successMixer && successTTF);
}
Beispiel #26
0
int main(int argc, char* argv[]) {
  if (SDL_Init(SDL_INIT_VIDEO) < 0) {
    printf("Can't initialize video \n");
    return 1;
  }

  if (TTF_Init() < 0) {
    printf("Can't initialize ttf \n");
    return 1;
  }

  lil_yuv_spec spec = lil_yuv420(3840, 2160);
  const size_t frame_size = lil_yuv_size(spec);
  const int frame_count = 500;
  int frame = 250;

  //yuv_video *video = yuv_video_alloc(argv[1], frame_size, frame_count);
  //yuv_video_read_frame(video, 0);

  //printf("Page size: %ld\n", );

  file_reader *reader = file_reader_alloc(argv[1]);
  if (!reader) {
    printf("Can't reader reader\n");
    return 1;
  }

  file_reader_map(reader, 0, frame_size);

  //TTF_Font *font = TTF_OpenFont("courier-new.ttf", 15);
  //This loads courier, but any font will do.
  //TTF_Font* font = loadfont("C:/windows/fonts/cour.ttf", 10);

  SDL_SetEventFilter(event_filter, NULL);

  atexit(SDL_Quit);
  int update_flag = 1;

  SDL_Window *window = SDL_CreateWindow(
        "An SDL2 window",
        SDL_WINDOWPOS_CENTERED,
        SDL_WINDOWPOS_CENTERED,
        2 * spec.width,
        spec.height,
        SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);

  const Uint32 windowID = SDL_GetWindowID(window);

  SDL_Renderer *renderer = SDL_CreateRenderer(window, -1, 0);
  SDL_RendererInfo info;
  SDL_GetRendererInfo(renderer, &info);
  printf("Renderer: %s\n", info.name);
  //SDL_RenderSetLogicalSize(renderer, width, height);
  SDL_Texture *texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_IYUV, SDL_TEXTUREACCESS_STREAMING, spec.width, spec.height);
  SDL_UpdateTexture(texture, NULL, file_reader_get(reader), spec.width);

  SDL_Color color = { 255, 255, 255, 255 };
  SDL_Color color2 = { 0, 0, 0, 128 };

  while (1)  {
    SDL_Event event;
    while (SDL_PollEvent(&event)) {
     // PrintEvent(&event);

      switch (event.type)  {
        case SDL_WINDOWEVENT:  {
          if (event.window.windowID == windowID)  {
            switch (event.window.event)  {
              case SDL_WINDOWEVENT_SIZE_CHANGED:  {
                const int width = event.window.data1;
                const int height = event.window.data2;
                update_flag = 1;
                break;
              }

              case SDL_WINDOWEVENT_CLOSE:  {
                event.type = SDL_QUIT;
                SDL_PushEvent(&event);
                break;
              }
            }
          }
          break;
        }

        case SDL_KEYDOWN: {
          switch (event.key.keysym.sym) {
          case SDLK_1:
            printf("1\n");
            SDL_SetWindowSize(window, 2 * spec.width, spec.height);
            break;
          case SDLK_2:
            printf("2\n");
            SDL_SetWindowSize(window, 2 * 2 * spec.width, 2 * spec.height);
            break;
          case SDLK_LEFT:
            if (frame > 0) {
              --frame;
              update_flag = 1;
            }
            break;
          case SDLK_RIGHT:
            if (frame < frame_count - 1) {
              ++frame;
              update_flag = 1;
            }
            break;
          }
          break;
        }

        case SDL_QUIT: {
          return 0;
        }
      }

      // after switch
      if (update_flag) {
        //yuv_video_read_frame(video, frame);
        if (!file_reader_map(reader, frame_size * frame, frame_size)) {
          perror("Can't map file\n");
        }
        SDL_UpdateTexture(texture, NULL, file_reader_get(reader), spec.width);

        char buf[100];
        sprintf(buf, "352 x 288\n%d/90\npsnr=43.4", frame);
        SDL_Texture *text = render_text(renderer, buf, "courier-new.ttf", color, 25);
        SDL_Texture *text2 = render_text(renderer, buf, "courier-new.ttf", color2, 25);

        SDL_Point size = {spec.width, spec.height};
        render_all(renderer, &size, texture, texture, text, text2);


        SDL_RenderPresent(renderer);
        SDL_DestroyTexture(text);
        SDL_DestroyTexture(text2);

        --update_flag;
      }
    }

    SDL_Delay(1);
  }

  SDL_DestroyWindow(window);

  SDL_Quit();


  //yuv_video_free(video);
  file_reader_free(reader);

  return 0;
}
Beispiel #27
0
int
MG_init_video (int width, int height, Uint32 video_flags)
{
  SDL_Surface *screen;
  int audio_rate = 22050;
  Uint16 audio_format = AUDIO_S16;	/* 16-bit stereo */
  int audio_channels = 2;
  int audio_buffers = 2048;

  machine = (MACHINE *) malloc (sizeof (MACHINE));
  memset (machine, 0, sizeof (MACHINE));
//  machine->use_audio = 1;

  if( !( SDL_WasInit( SDL_INIT_VIDEO ) & SDL_INIT_VIDEO ) )
    {
      printf("SDL was not inited yet ... initing\n");

      if( !SDL_Init (SDL_INIT_VIDEO | SDL_INIT_AUDIO) )
      {
	if (TTF_Init () == -1)
	  {
	    printf ("Unable to start TTF rendering\n");
	    SDL_Quit ();
	  }
      }
      else
	{
	  printf("err: can not set up SDL\n");
	  SDL_Quit();
	  return -1;
	}
    }
  else
    {
      printf("SDL was already inited\n");
    }

  screen = SDL_SetVideoMode (width, height, 32, video_flags);
  if (!screen)
    {
      printf ("[FATAL] can not set video mode properly!\n");
      exit (-1);
    }

  Mix_VolumeMusic(SDL_MIX_MAXVOLUME);

  if( Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 1, 2048) ){
	  printf("[ERROR] Unable to open audio!\n");
	  exit(-1);
  }

  Mix_ChannelFinished(on_mix_halt);

  machine->screen = screen;

  if( !machine->game_world )
    {
      machine->game_world = SDL_CreateRGBSurface( SDL_SWSURFACE, width, height,
						  screen->format->BitsPerPixel,
						  screen->format->Rmask, screen->format->Gmask,
						  screen->format->Bmask, screen->format->Amask
						  );
    }

  SDL_Rect v = {0,0,machine->screen->w , machine->screen->h };
  MG_set_view_rect( v );

  MG_get_keys ();
  return 0;
}
void InterfacePricipale(sJoueur *Perso, sMESS_ITEMS *item_data)
{


        //Initiaisation
   TTF_Init();
   int viePerdu=200,manaPerdu=300,manaFinal=0,vieFinal=0,vieTotale=800,manaTotale=800,xpTotal=800,xpManquant=700,xpFinal=0,xpFinal2=0,xpFinalTotal;
   SDL_Rect position,positionBarreDeVieIP,positionBarreDeManaIP,decoupeV,decoupeM,decoupeXP1,decoupeXP2,positionCurseur1,positionCurseur2,
   positionTexte,positionTexte2,positionTexte3,positionTexte4,positionTexte5,positionTexte6,positionBarreXP1IP,positionBarreXP2IP,positionFOR,positionAGI,positionDEF,positionINT,positionDEX,positionCHA;
   vieFinal=(viePerdu*793)/vieTotale;
   manaFinal=(manaPerdu*773)/manaTotale;
   xpFinalTotal=(xpManquant*1463)/xpTotal;



        //Affichage ecran
   SDL_Init(SDL_INIT_VIDEO);
   SDL_Surface* ecran = NULL;
   ecran=SDL_SetVideoMode(640,480,32,SDL_HWSURFACE/*|SDL_FULLSCREEN*/);
   SDL_FillRect(ecran,NULL,SDL_MapRGB(ecran->format,0,0,0));

         //Affichage Map interface
   SDL_Surface* interface =NULL;
   interface= SDL_LoadBMP("Sprites/IP/Interface principale.bmp");
   position.x=0;
   position.y=0;

        //Affichage Barre de vie et Mana
   SDL_Surface* barreVie = NULL,*barreMana = NULL;
   barreMana = SDL_LoadBMP("Sprites/IP/Barre De Mana IP.bmp");
   barreVie = SDL_LoadBMP("Sprites/IP/Barre De Vie IP.bmp");
   SDL_SetColorKey(barreVie, SDL_SRCCOLORKEY, SDL_MapRGB(barreVie->format, 0, 0, 255));
   SDL_SetColorKey(barreMana, SDL_SRCCOLORKEY, SDL_MapRGB(barreMana->format, 0, 0, 255));
   positionBarreDeManaIP.x=855;
   positionBarreDeManaIP.y=0;
   decoupeM.x=0;
   decoupeM.y=0;
   decoupeM.w=805;
   decoupeM.h=181;
   positionBarreDeVieIP.x=22+vieFinal;
   positionBarreDeVieIP.y=0;
   decoupeV.x=vieFinal;
   decoupeV.y=0;
   decoupeV.w=815;
   decoupeV.h=181;

       //Affichage Barre d'XP

SDL_Surface* barreXP1 = NULL,*barreXP2 = NULL;
barreXP1 = SDL_LoadBMP("Sprites/IP/Barre d'XP 1 IP.bmp");
barreXP2 = SDL_LoadBMP("Sprites/IP/Barre d'XP 2 IP.bmp");
SDL_SetColorKey(barreXP1, SDL_SRCCOLORKEY, SDL_MapRGB(barreXP1->format, 0, 0, 255));
SDL_SetColorKey(barreXP2, SDL_SRCCOLORKEY, SDL_MapRGB(barreXP2->format, 0, 0, 255));
  if (xpFinalTotal>725)
    {
        xpFinal2=725;
        xpFinal=xpFinalTotal-738;
    }
  else
    {
        xpFinal2=xpFinalTotal;
        xpFinal=0;
    }
positionBarreXP1IP.x=5;
positionBarreXP1IP.y=0;
decoupeXP1.x=0;
decoupeXP1.y=0;
decoupeXP1.w=738-xpFinal;
decoupeXP1.h=197;
positionBarreXP2IP.x=950;
positionBarreXP2IP.y=0;
decoupeXP2.x=0;
decoupeXP2.y=0;
decoupeXP2.w=725-xpFinal2;
decoupeXP2.h=197;

        //Affichage curseur1
   SDL_Surface* curseur1 =NULL;
   curseur1= SDL_LoadBMP("Sprites/IP/curseur1 IP.bmp");
SDL_SetColorKey(curseur1, SDL_SRCCOLORKEY, SDL_MapRGB(curseur1->format, 0, 0, 255));

        //Afichage curseur2
SDL_Surface* curseur2 =NULL;
   curseur2= SDL_LoadBMP("Sprites/IP/curseur2 IP.bmp");
SDL_SetColorKey(curseur2, SDL_SRCCOLORKEY, SDL_MapRGB(curseur2->format, 0, 0, 255));

       //Initialisation police
SDL_Surface *texte =NULL,*texte2 =NULL,*texte3 =NULL,*texte4 =NULL,*texte5 =NULL,*texte6 =NULL,*FOR=NULL,*AGI=NULL,*DEF=NULL,*INT=NULL,*DEX=NULL,*CHA=NULL;
TTF_Font *police= NULL;
police = TTF_OpenFont("carolingia.ttf" ,90);
SDL_Color noire = {135,65,14};
positionTexte.x=25;
positionTexte.y=290;
texte = TTF_RenderText_Blended(police ,"INVENTAIRE",noire);
positionTexte2.x=25;
positionTexte2.y=485;
texte2 = TTF_RenderText_Blended(police ,"STATISTIQUES",noire);
positionTexte3.x=25;
positionTexte3.y=665;
texte3 = TTF_RenderText_Blended(police ,"CARTE",noire);
positionTexte4.x=1350;
positionTexte4.y=295;
texte4 = TTF_RenderText_Blended(police ,"SORTS",noire);
positionTexte5.x=967;
positionTexte5.y=490;
texte5 = TTF_RenderText_Blended(police ,"COMPETENCE",noire);
positionTexte6.x=1260;positionTexte2;
positionTexte6.y=665;
texte6 = TTF_RenderText_Blended(police ,"RETOUR",noire);

positionFOR.x=25;
positionFOR.y=850;
FOR = TTF_RenderText_Blended(police ,"FOR",noire);
positionAGI.x=275;
positionAGI.y=855;
AGI = TTF_RenderText_Blended(police ,"AGI",noire);
positionDEF.x=485;
positionDEF.y=854;
DEF = TTF_RenderText_Blended(police ,"DEF",noire);
positionINT.x=1000;
positionINT.y=853;
INT = TTF_RenderText_Blended(police ,"INT",noire);
positionDEX.x=1225;
positionDEX.y=852;
DEX = TTF_RenderText_Blended(police ,"DEX",noire);
positionCHA.x=1470;
positionCHA.y=851;
CHA = TTF_RenderText_Blended(police ,"CHA",noire);

//Blit Statique
 SDL_BlitSurface(FOR,NULL,interface,&positionFOR);
 SDL_BlitSurface(AGI,NULL,interface,&positionAGI);
 SDL_BlitSurface(DEF,NULL,interface,&positionDEF);
 SDL_BlitSurface(INT,NULL,interface,&positionINT);
 SDL_BlitSurface(DEX,NULL,interface,&positionDEX);
 SDL_BlitSurface(CHA,NULL,interface,&positionCHA);
 SDL_BlitSurface(texte,NULL,interface,&positionTexte);
 SDL_BlitSurface(texte2,NULL,interface,&positionTexte2);
 SDL_BlitSurface(texte3,NULL,interface,&positionTexte3);
 SDL_BlitSurface(texte4,NULL,interface,&positionTexte4);
 SDL_BlitSurface(texte5,NULL,interface,&positionTexte5);
 SDL_BlitSurface(texte6,NULL,interface,&positionTexte6);




         //Gestion Evenement

 int continuerIP = 1;
    SDL_Event event;


    while (continuerIP)
{
    SDL_WaitEvent(&event);
    switch(event.type)
    {
        case SDL_KEYDOWN:

            switch (event.key.keysym.sym)
               {
                  case SDLK_ESCAPE:
                    continuerIP=0;
                    break;

                  default:
                    ;

               }
               break;

        case SDL_MOUSEMOTION:

            if (event.motion.x>=0 && event.motion.y>=275 && event.motion.x<=740 && event.motion.y<=400)
                {
                    positionCurseur1.x=723;
                    positionCurseur1.y=282;

                }

            else if (event.motion.x>=0 && event.motion.y>=462 && event.motion.x<=740 && event.motion.y<=595)
                {
                    positionCurseur1.x=724;
                    positionCurseur1.y=471;

                }
            else if (event.motion.x>=0 && event.motion.y>=645 && event.motion.x<=740 && event.motion.y<=780)
                {
                    positionCurseur1.x=729;
                    positionCurseur1.y=654;

                }
            else if (event.motion.x>=950 && event.motion.y>=275 && event.motion.x<=1680 && event.motion.y<=400)
                {
                    positionCurseur2.x=900;
                    positionCurseur2.y=278;

                }
            else if (event.motion.x>=950 && event.motion.y>=462 && event.motion.x<=1680 && event.motion.y<=595)
                {
                   positionCurseur2.x=899;
                   positionCurseur2.y=470;

                }
            else if (event.motion.x>=950 && event.motion.y>=645 && event.motion.x<=1680 && event.motion.y<=780)
                {
                    positionCurseur2.x=900;
                    positionCurseur2.y=649;

                }
            else
                {
                    positionCurseur1.x=1680;
                    positionCurseur1.y=1050;
                    positionCurseur2.x=1680;
                    positionCurseur2.y=1050;
                }

              break;

        case SDL_MOUSEBUTTONUP:

            if (event.button.x>=0 && event.button.y>=275 && event.button.x<=740 && event.button.y<=400)
                {
                    Inventaire(Perso, item_data);
                }
            else if (event.button.x>=0 && event.button.y>=462 && event.button.x<=740 && event.button.y<=595)
                {

                }
            else if (event.button.x>=0 && event.button.y>=645 && event.button.x<=740 && event.button.y<=780)
                {

                }
            else if (event.button.x>=950 && event.button.y>=275 && event.button.x<=1680 && event.button.y<=400)
                {

                }
            else if (event.button.x>=950 && event.button.y>=462 && event.button.x<=1680 && event.button.y<=595)
                {

                }
            else if (event.button.x>=950 && event.button.y>=645 && event.button.x<=1680 && event.button.y<=780)
                {
                    continuerIP=0;
                }

        break;
    break;
    }
      // Blit et refresh

 SDL_BlitSurface(interface,NULL,ecran,&position);
 SDL_BlitSurface(barreVie,&decoupeV,ecran,&positionBarreDeVieIP);
 SDL_BlitSurface(barreMana,&decoupeM,ecran,&positionBarreDeManaIP);
 SDL_BlitSurface(barreXP1,&decoupeXP1,ecran,&positionBarreXP1IP);
 SDL_BlitSurface(barreXP2,&decoupeXP2,ecran,&positionBarreXP2IP);
 SDL_BlitSurface(curseur1,NULL,ecran,&positionCurseur1);
 SDL_BlitSurface(curseur2,NULL,ecran,&positionCurseur2);


   SDL_Flip(ecran);
   SDL_Flip(curseur1);
   SDL_Flip(curseur2);
}

        //Fin systeme
   SDL_FreeSurface(interface);
   SDL_FreeSurface(ecran);
   SDL_FreeSurface(curseur1);
   SDL_FreeSurface(curseur2);
   SDL_FreeSurface(texte);
   SDL_FreeSurface(texte2);
   SDL_FreeSurface(texte3);
   SDL_FreeSurface(texte4);
   SDL_FreeSurface(texte5);
   SDL_FreeSurface(texte6);
   SDL_FreeSurface(FOR);
   SDL_FreeSurface(AGI);
   SDL_FreeSurface(DEF);
   SDL_FreeSurface(INT);
   SDL_FreeSurface(DEX);
   SDL_FreeSurface(CHA);
   SDL_FreeSurface(barreVie);
   SDL_FreeSurface(barreMana);
   SDL_FreeSurface(barreXP1);
   SDL_FreeSurface(barreXP2);
}
Beispiel #29
0
int main(int argc, char** argv) {
    //Start up SDL and make sure it went ok
    if (SDL_Init(SDL_INIT_EVERYTHING) == -1) {
        std::cout << SDL_GetError() << std::endl;
        return 1;
    }
    if (TTF_Init() == -1) {
        std::cout << TTF_GetError() << std::endl;
        return 2;
    }

    //Setup our window and renderer
    window = SDL_CreateWindow("Lesson 6", SDL_WINDOWPOS_CENTERED,
                              SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
    if (window == nullptr) {
        std::cout << SDL_GetError() << std::endl;
        return 2;
    }
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED
                                  | SDL_RENDERER_PRESENTVSYNC);
    if (renderer == nullptr) {
        std::cout << SDL_GetError() << std::endl;
        return 3;
    }

    //The textures we'll be using
    SDL_Texture *image = nullptr;
    try {
        SDL_Color color = { 255, 255, 255 };
        image = RenderText("TTF fonts are cool!", "../res/Lesson6/SourceSansPro-Regular.ttf", color, 64);
    }
    catch (const std::runtime_error &e) {
        std::cout << e.what() << std::endl;
        return 4;
    }
    //Our texture size won't change, so we can get it here
    //instead of constantly allocating/deleting ints in the loop
    int iW, iH;
    SDL_QueryTexture(image, NULL, NULL, &iW, &iH);
    int x = SCREEN_WIDTH / 2 - iW / 2;
    int y = SCREEN_HEIGHT / 2 - iH / 2;

    //Our event type
    SDL_Event e;

    //For tracking if we want to quit
    bool quit = false;
    while (!quit) {
        //Event Polling
        while (SDL_PollEvent(&e)) {
            //If user closes he window
            if (e.type == SDL_QUIT)
                quit = true;
            //If user presses any key
            if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)
                quit = true;
        }
        //Rendering
        SDL_RenderClear(renderer);
        //Draw the image
        ApplySurface(x, y, image, renderer);

        //Update the screen
        SDL_RenderPresent(renderer);
    }

    //Destroy the various items
    SDL_DestroyTexture(image);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);

    SDL_Quit();

    return 0;
}
Beispiel #30
0
/**
 * \brief Initializes the font system.
 */
void FontResource::initialize() {

  TTF_Init();
}