#include #include #include "pong.h" Pong* Pong_init() { Pong *p = malloc(sizeof(Pong)); // Cast away the const *(int *)&p->SCREEN_WIDTH = 640; *(int *)&p->SCREEN_HEIGHT = 480; p->ball = Ball_init(p->SCREEN_WIDTH, p->SCREEN_HEIGHT); p->racketL = Racket_init(p->SCREEN_WIDTH, p->SCREEN_HEIGHT, 50, 50, SDL_SCANCODE_E, SDL_SCANCODE_D); p->racketR = Racket_init(p->SCREEN_WIDTH, p->SCREEN_HEIGHT, p->SCREEN_WIDTH - 50, 50, SDL_SCANCODE_I, SDL_SCANCODE_K); p->window = SDL_CreateWindow( "Pong", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, p->SCREEN_WIDTH, p->SCREEN_HEIGHT, SDL_WINDOW_SHOWN ); if( p->window == NULL ) { printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() ); Pong_free(p); return NULL; } p->renderer = SDL_CreateRenderer(p->window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); p->screenSurface = SDL_GetWindowSurface( p->window ); SDL_FillRect( p->screenSurface, NULL, SDL_MapRGB( p->screenSurface->format, 0, 0, 0 ) ); SDL_UpdateWindowSurface( p->window ); return p; } void Pong_free(Pong *p) { SDL_DestroyRenderer(p->renderer); SDL_DestroyWindow(p->window); Ball_free(p->ball); Racket_free(p->racketL); Racket_free(p->racketR); free(p); } void Pong_clear(Pong *p) { SDL_SetRenderDrawColor(p->renderer, 0, 0, 0, 255 ); SDL_RenderClear( p->renderer ); } void Pong_render(Pong *p) { Pong_clear(p); Ball_render(p->ball, p->renderer); Racket_render(p->racketL, p->renderer); Racket_render(p->racketR, p->renderer); SDL_RenderPresent(p->renderer); } void Ball_move(Ball *b, Pong *p) { b->posX += b->velX; if (Ball_collision(b, p->racketL) || Ball_collision(b, p->racketR)) { b->posX -= b->velX; b->velX = -b->velX; } if (b->posX < 0) { p->racketR->score++; Ball_reset(b, -1); } else if(b->posX + b->BALL_WIDTH > b->SCREEN_WIDTH) { p->racketL->score++; Ball_reset(b, 1); } b->posY += b->velY; if ((b->posY < 0) || (b->posY + b->BALL_HEIGHT > b->SCREEN_HEIGHT)) { b->posY -= b->velY; b->velY = -b->velY; } } void Pong_run(Pong *p) { int quit = false; while (!quit) { while( SDL_PollEvent( &(p->e) ) != 0 ) { if( p->e.type == SDL_QUIT) quit = true; } const Uint8* currentKeyStates = SDL_GetKeyboardState( NULL ); if (currentKeyStates[SDL_SCANCODE_ESCAPE]) quit = true; Racket_handle_event(p->racketL, currentKeyStates); Racket_handle_event(p->racketR, currentKeyStates); Ball_move(p->ball, p); Racket_move(p->racketL); Racket_move(p->racketR); Pong_render(p); Pong_score_run(p); } Pong_score_end(p); } void Pong_score(const Pong *p, char c) { printf("SCORE: L %i | R %i", p->racketL->score, p->racketR->score); putc(c, stdout); } void Pong_score_run(const Pong *p) { Pong_score(p, '\r'); fflush(stdout); } void Pong_score_end(const Pong *p) { Pong_score(p, '\n'); }