From 32eea495d896274a08f22fffcffcb6990f5be202 Mon Sep 17 00:00:00 2001 From: Anthony Debucquoy Date: Sun, 24 Mar 2024 15:01:24 +0100 Subject: [PATCH] first commit --- Makefile | 28 +++++++++++++++++++ pong.c | 84 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 Makefile create mode 100644 pong.c diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..e695c79 --- /dev/null +++ b/Makefile @@ -0,0 +1,28 @@ +.PHONY: all clean run +VERSION = 0.0.1 + +LIBS = sdl2 +CMACRO = -DVERSION=\"$(VERSION)\" + +CC = gcc +CFLAGS = -g -Wall -Wextra -pedantic $(shell pkg-config $(LIBS) --cflags) $(CMACRO) +LDFLAGS = $(shell pkg-config $(LIBS) --libs) -lm + +all: pong + +pong: pong.o + $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) + +%.o: %.c + $(CC) $(CFLAGS) -c -o $@ $< + +clean: + rm -f *.o + rm -f pong + +bear: clean + bear -- make + +run: pong + ./$< + diff --git a/pong.c b/pong.c new file mode 100644 index 0000000..1ff743a --- /dev/null +++ b/pong.c @@ -0,0 +1,84 @@ +#include +#include +#include +#include +#include +#include + +#include + +#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; +}