main.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Author : Jovian HERSEMEULE
  2. #include <iostream>
  3. #include <SDL/SDL.h>
  4. int main()
  5. {
  6. /// [1] Start
  7. // [1.1] Start SDL
  8. if ( SDL_Init( SDL_INIT_VIDEO ) < 0)
  9. {
  10. std::cout << "Can't initialize SDL: " << SDL_GetError() << std::endl;
  11. return 1;
  12. }
  13. // [1.2] Anticipate quit
  14. atexit(SDL_Quit);
  15. // [1.3] Set title
  16. SDL_WM_SetCaption("Application SDL", 0);
  17. /// [2] Create components
  18. // [2.1] Create window
  19. const int width(640), height(480);
  20. SDL_Surface* screen = SDL_SetVideoMode(width, height, 32, SDL_HWSURFACE|SDL_DOUBLEBUF);
  21. if ( !screen )
  22. {
  23. std::cout << "Unable to set " << width << "x" << height << " video: " << SDL_GetError() << std::endl;
  24. return 1;
  25. }
  26. // [2.2] Other components
  27. SDL_Surface* grass = SDL_LoadBMP("textures/grass.bmp");
  28. SDL_Surface* pawn = SDL_LoadBMP("textures/pawn.bmp");
  29. SDL_Rect pos({0, 0, 0, 0});
  30. SDL_Rect pawnPos({0, 0, 0, 0});
  31. /// [3] Main loop
  32. bool done(false);
  33. while (!done)
  34. {
  35. // [3.1] Events
  36. SDL_Event event;
  37. while (SDL_PollEvent(&event))
  38. {
  39. switch (event.type)
  40. {
  41. case SDL_QUIT:
  42. done = true;
  43. break;
  44. case SDL_KEYDOWN:
  45. if (event.key.keysym.sym == SDLK_ESCAPE)
  46. done = true;
  47. break;
  48. case SDL_MOUSEMOTION:
  49. pawnPos.x = event.motion.x - pawn->w / 2;
  50. pawnPos.y = event.motion.y - pawn->h / 2;
  51. break;
  52. } // end switch event type
  53. } // end of message processing
  54. // [3.2] Compute
  55. // Nothing for now
  56. // [3.3] Draw phase
  57. SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 255, 255));
  58. for (pos.y = 0; pos.y < height; pos.y += grass->h)
  59. for (pos.x = 0; pos.x < width; pos.x += grass->w)
  60. SDL_BlitSurface(grass, NULL, screen, &pos);
  61. SDL_BlitSurface(pawn, NULL, screen, &pawnPos);
  62. SDL_Flip(screen);
  63. SDL_Delay(16);
  64. } // end of main loop
  65. ///[4] Free components
  66. SDL_FreeSurface(grass);
  67. SDL_FreeSurface(pawn);
  68. SDL_FreeSurface(screen);
  69. std::cout << "No error caught." << std::endl;
  70. return 0;
  71. }