#include #include SDL_Rect map_rect(int x, int y, int w, int h) { SDL_Rect tmp; tmp.x = x; tmp.y = y; tmp.w = w; tmp.h = h; return tmp; } bool between(int which, int range_a, int range_b) { int a = (range_a > range_b) ? range_a : range_b; int b = (range_a > range_b) ? range_b : range_a; if(which <= a) { if(which >= b) { return true; } } return false; } int main(int argc, char * argv[]) { SDL_Init(SDL_INIT_VIDEO); SDL_Surface * screen = SDL_SetVideoMode(640,480,32,SDL_DOUBLEBUF); bool done = false; SDL_Event event; int player1_y = 0; int player2_y = 0; int player1_score = 0; int player2_score = 0; int ball_x = 50, ball_y = 50; int ballspeed_x = 2, ballspeed_y = 2; SDL_Rect destination; Uint32 old_ticks = SDL_GetTicks(); Uint32 new_ticks = old_ticks; while(!done) { old_ticks = SDL_GetTicks(); SDL_FillRect(SDL_GetVideoSurface(),NULL,SDL_MapRGB(SDL_GetVideoSurface()->format,0,0,255)); destination = map_rect(5,player1_y, 10, 50); SDL_FillRect(SDL_GetVideoSurface(),&destination, SDL_MapRGB(SDL_GetVideoSurface()->format,0,0,0)); destination = map_rect(ball_x,ball_y,5,5); SDL_FillRect(SDL_GetVideoSurface(),&destination, SDL_MapRGB(SDL_GetVideoSurface()->format,255,255,255)); destination = map_rect(screen->w - 15, player2_y, 10, 50); SDL_FillRect(SDL_GetVideoSurface(),&destination, SDL_MapRGB(SDL_GetVideoSurface()->format,0,0,0)); SDL_Flip(SDL_GetVideoSurface()); while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) { done = true; } if(event.type == SDL_KEYDOWN) { if(event.key.keysym.sym == SDLK_ESCAPE) { done = true; } } } if(SDL_GetKeyState(NULL)[SDLK_DOWN]) { player1_y += 1; } if(SDL_GetKeyState(NULL)[SDLK_UP]) { player1_y -= 1; } if(ball_y > player2_y + 25) { player2_y += 1; } if(ball_y < player2_y + 25) { player2_y -= 1; } ball_x += ballspeed_x; ball_y += ballspeed_y; if(ball_y < 0 && ballspeed_y < 0) ballspeed_y *= -1; if(ball_y > screen->h && ballspeed_y > 0) ballspeed_y *= -1; if(ball_x < 0 && ballspeed_x < 0) { ballspeed_x *= -1; player2_score += 1; std::cout << "They scored! :( They have " << player2_score << " points.\n"; } if(ball_x > screen->w && ballspeed_x > 0) { ballspeed_x *= -1; player1_score += 1; std::cout << "You scored! You have " << player1_score << " points.\n"; } if(ball_x < 15) { if(between(ball_y, player1_y, player1_y+50)) { if(ballspeed_x < 0) { ballspeed_x *= -1; } } } if(ball_x > screen->w - 15) { if(between(ball_y,player2_y, player2_y+50)) { if(ballspeed_x > 0) { ballspeed_x *= -1; } } } new_ticks = SDL_GetTicks(); if(new_ticks - old_ticks < 17) { SDL_Delay(17 - (new_ticks-old_ticks)); } } return 0; }