Created
January 27, 2021 00:46
-
-
Save davemenninger/bc62d13d81d6c9effd409b0b3aa695ff to your computer and use it in GitHub Desktop.
SDL2 Demo in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SDL2/SDL.h> | |
#include <stdio.h> | |
/* Screen dimension constants */ | |
const int SCREEN_WIDTH = 640; | |
const int SCREEN_HEIGHT = 480; | |
int error(char *msg, const char *err) { | |
printf("Error %s: %s\n", msg, err); | |
return 1; | |
} | |
int main(int argc, char *args[]) { | |
(void)argc; | |
(void)args; | |
SDL_Window *window = NULL; | |
SDL_Surface *surface = NULL; | |
if (SDL_Init(SDL_INIT_VIDEO) < 0) | |
return error("init", SDL_GetError()); | |
window = SDL_CreateWindow("A Really Cool Game", SDL_WINDOWPOS_UNDEFINED, | |
SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, | |
SCREEN_HEIGHT, SDL_WINDOW_SHOWN); | |
if (window == NULL) | |
return error("window", SDL_GetError()); | |
Uint32 render_flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC; | |
SDL_Renderer *rend = SDL_CreateRenderer(window, -1, render_flags); | |
SDL_RenderClear(rend); | |
SDL_bool quit = SDL_FALSE; | |
SDL_Event event; | |
SDL_Rect rect; | |
rect.x = 250; | |
rect.y = 150; | |
rect.w = 200; | |
rect.h = 200; | |
int right = 0; | |
int left = 0; | |
while (!quit) { | |
while (SDL_PollEvent(&event)) { | |
switch (event.type) { | |
case SDL_QUIT: | |
quit = SDL_TRUE; | |
break; | |
case SDL_KEYUP: | |
switch (event.key.keysym.scancode) { | |
case SDL_SCANCODE_D: | |
case SDL_SCANCODE_RIGHT: | |
right = 0; | |
break; | |
case SDL_SCANCODE_A: | |
case SDL_SCANCODE_LEFT: | |
left = 0; | |
break; | |
default: | |
(void)0; | |
} | |
break; | |
case SDL_KEYDOWN: | |
switch (event.key.keysym.scancode) { | |
case SDL_SCANCODE_D: | |
case SDL_SCANCODE_RIGHT: | |
right = 1; | |
break; | |
case SDL_SCANCODE_A: | |
case SDL_SCANCODE_LEFT: | |
left = 1; | |
break; | |
default: | |
(void)0; | |
} | |
break; | |
default: | |
(void)0; | |
} | |
} | |
if (right == 1) { | |
rect.x += 1; | |
} | |
if (left == 1) { | |
rect.x -= 1; | |
} | |
rect.x = rect.x % (SCREEN_WIDTH - rect.w); | |
if (rect.x < 0) | |
rect.x = SCREEN_WIDTH - rect.w; | |
/* do stuff */ | |
SDL_RenderClear(rend); | |
SDL_SetRenderDrawColor(rend, 255, 255, 255, 255); | |
SDL_RenderFillRect(rend, &rect); | |
SDL_RenderDrawRect(rend, &rect); | |
SDL_SetRenderDrawColor(rend, 0, 0, 0, 255); | |
SDL_RenderPresent(rend); | |
SDL_Delay(1000 / 60); | |
} | |
/* close */ | |
SDL_FreeSurface(surface); | |
surface = NULL; | |
SDL_DestroyWindow(window); | |
window = NULL; | |
SDL_Quit(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment