main.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * rectangles.c
  3. * written by Holmes Futrell
  4. * use however you want
  5. */
  6. #include "SDL.h"
  7. #include <time.h>
  8. #define SCREEN_WIDTH 320
  9. #define SCREEN_HEIGHT 480
  10. int
  11. randomInt(int min, int max)
  12. {
  13. return min + rand() % (max - min + 1);
  14. }
  15. void
  16. render(SDL_Renderer *renderer)
  17. {
  18. Uint8 r, g, b;
  19. /* Clear the screen */
  20. SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
  21. SDL_RenderClear(renderer);
  22. /* Come up with a random rectangle */
  23. SDL_Rect rect;
  24. rect.w = randomInt(64, 128);
  25. rect.h = randomInt(64, 128);
  26. rect.x = randomInt(0, SCREEN_WIDTH);
  27. rect.y = randomInt(0, SCREEN_HEIGHT);
  28. /* Come up with a random color */
  29. r = randomInt(50, 255);
  30. g = randomInt(50, 255);
  31. b = randomInt(50, 255);
  32. SDL_SetRenderDrawColor(renderer, r, g, b, 255);
  33. /* Fill the rectangle in the color */
  34. SDL_RenderFillRect(renderer, &rect);
  35. /* update screen */
  36. SDL_RenderPresent(renderer);
  37. }
  38. int
  39. main(int argc, char *argv[])
  40. {
  41. SDL_Window *window;
  42. SDL_Renderer *renderer;
  43. int done;
  44. SDL_Event event;
  45. /* initialize SDL */
  46. if (SDL_Init(SDL_INIT_VIDEO) < 0) {
  47. printf("Could not initialize SDL\n");
  48. return 1;
  49. }
  50. /* seed random number generator */
  51. srand(time(NULL));
  52. /* create window and renderer */
  53. window =
  54. SDL_CreateWindow(NULL, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT,
  55. SDL_WINDOW_OPENGL);
  56. if (!window) {
  57. printf("Could not initialize Window\n");
  58. return 1;
  59. }
  60. renderer = SDL_CreateRenderer(window, -1, 0);
  61. if (!renderer) {
  62. printf("Could not create renderer\n");
  63. return 1;
  64. }
  65. /* Enter render loop, waiting for user to quit */
  66. done = 0;
  67. while (!done) {
  68. while (SDL_PollEvent(&event)) {
  69. if (event.type == SDL_QUIT) {
  70. done = 1;
  71. }
  72. }
  73. render(renderer);
  74. SDL_Delay(1);
  75. }
  76. /* shutdown SDL */
  77. SDL_Quit();
  78. return 0;
  79. }