Pong/src/Game.h

106 lines
2.9 KiB
C
Raw Normal View History

2024-01-19 15:06:48 +01:00
//
// Created by love on 2024-01-18.
//
#pragma
#include "SdlWrapper.h"
#include "SDL.h"
#include "VisibleObjects/Ball.h"
#include "VisibleObjects/PlayerPaddle.h"
2024-01-19 18:41:26 +01:00
#include "VisibleObjects/Score.h"
2024-01-19 15:06:48 +01:00
class Game : public SdlWrapper {
private:
Ball *ball;
2024-01-19 18:41:26 +01:00
Score *score;
2024-01-19 15:06:48 +01:00
PlayerPaddle *leftPaddle, *rightPaddle;
public:
explicit Game(SDL_Point screenSize) : SdlWrapper("Pong", screenSize, 60) {
leftPaddle = new PlayerPaddle(&this->screenSize, Side::LEFT);
rightPaddle = new PlayerPaddle(&this->screenSize, Side::RIGHT);
2024-01-19 18:41:26 +01:00
auto func = [this](Side side) {
const char *player = side == Side::LEFT ? "one" : "two";
std::cout << "Player " << player << " won" << std::endl;
this->running = false;
};
score = new Score(5, &this->screenSize, func);
ball = new Ball(&this->screenSize, leftPaddle, rightPaddle, score);
2024-01-19 15:06:48 +01:00
}
~Game() override {
delete ball;
delete leftPaddle;
delete rightPaddle;
2024-01-19 18:41:26 +01:00
delete score;
2024-01-19 15:06:48 +01:00
}
void draw(SDL_Renderer *renderer) override {
// Background
SDL_SetRenderDrawColor(renderer, 128, 0, 128, 0);
SDL_RenderClear(renderer);
ball->draw(renderer);
2024-01-19 18:41:26 +01:00
score->draw(renderer);
2024-01-19 15:06:48 +01:00
leftPaddle->draw(renderer);
rightPaddle->draw(renderer);
SDL_RenderPresent(renderer);
}
bool update() override {
ball->update();
leftPaddle->update();
rightPaddle->update();
2024-01-19 18:41:26 +01:00
score->update();
2024-01-19 15:06:48 +01:00
return true;
}
bool handleEvents() override {
SDL_Event event;
while (SDL_PollEvent(&event) != 0) {
if (event.type == SDL_QUIT)
return false;
if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_w:
leftPaddle->startMoving(true);
break;
case SDLK_s:
leftPaddle->startMoving(false);
break;
case SDLK_UP:
rightPaddle->startMoving(true);
break;
case SDLK_DOWN:
rightPaddle->startMoving(false);
break;
}
} else if (event.type == SDL_KEYUP) {
switch (event.key.keysym.sym) {
case SDLK_w:
leftPaddle->stopMoving(true);
break;
case SDLK_s:
leftPaddle->stopMoving(false);
break;
case SDLK_UP:
rightPaddle->stopMoving(true);
break;
case SDLK_DOWN:
rightPaddle->stopMoving(false);
break;
}
}
}
return true;
}
};