pong/pong.c

85 lines
1.8 KiB
C
Raw Permalink Normal View History

2024-03-24 15:01:24 +01:00
#include <SDL2/SDL.h>
#include <SDL2/SDL_error.h>
#include <SDL2/SDL_events.h>
#include <SDL2/SDL_rect.h>
#include <SDL2/SDL_render.h>
#include <SDL2/SDL_video.h>
#include <unistd.h>
#define WIDTH 1920
#define HEIGHT 1200
#define BALLSIZE 50
SDL_Window *win;
SDL_Renderer *ren;
struct {
int x, y;
float dx, dy;
} ballPos = {10, 10, 3, 2};
void* cpv(void * v, const char *msg){
if( v == 0 ){
fprintf(stderr, "%s -> %s\n",msg, SDL_GetError());
exit(1);
}
return v;
}
int civ(int v, const char *msg){
if( v != 0 ){
fprintf(stderr, "%s -> %s\n",msg, SDL_GetError());
exit(1);
}
return v;
}
void ballMove(){
if(ballPos.x <=0 || ballPos.x >= WIDTH - BALLSIZE){
ballPos.dx = ballPos.dx * -1;
ballPos.dy = (ballPos.dy / abs(ballPos.dy)) * ((rand() % 5) + 1);
}
if(ballPos.y <=0 || ballPos.y >= HEIGHT - BALLSIZE){
ballPos.dy = ballPos.dy * -1;
ballPos.dx = (ballPos.dx / abs(ballPos.dx)) * ((rand() % 5) + 1);
}
ballPos.x = ballPos.x + ballPos.dx;
ballPos.y = ballPos.y + ballPos.dy;
}
int main()
{
civ(SDL_Init(SDL_INIT_VIDEO), "can't init SDL");
win = cpv(SDL_CreateWindow("pong", 0, 0, WIDTH, HEIGHT, SDL_WINDOW_SHOWN), "can't create window");
ren = cpv(SDL_CreateRenderer(win, -1, SDL_RENDERER_SOFTWARE), "can't create renderer");
int i = 0;
SDL_RenderClear(ren);
SDL_bool should_close = SDL_FALSE;
SDL_Event e;
while(!should_close){
while(SDL_PollEvent(&e)){
if(e.type == SDL_QUIT){
should_close = SDL_TRUE;
}
}
/* SDL_SetRenderDrawColor(ren, 0, 0, 0, 255); */
/* SDL_RenderClear(ren); */
ballMove();
SDL_SetRenderDrawColor(ren, (sin((double)i/20) + 1) * 128, (cos((double)i/10) + 1) * 128, (sin((double)i/50) + 1) * 128, 255);
SDL_Rect ball = {ballPos.x, ballPos.y, BALLSIZE, BALLSIZE};
SDL_RenderFillRect(ren, &ball);
SDL_RenderPresent(ren);
i++;
}
return 0;
}