refactor event handling

This commit is contained in:
Love 2024-01-30 10:54:25 +01:00
parent 9c77a9fde6
commit de58a7f405
4 changed files with 69 additions and 55 deletions

View File

@ -80,64 +80,53 @@ void Game::update() {
}
}
bool Game::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT)
return false;
switch (gameState) {
case GameState::START_SCREEN:
startScreen->handleEvent(event);
break;
case GameState::GAME:
handleGameEvent(event);
break;
case GameState::END_SCREEN:
if (event.type == SDL_KEYDOWN && !endScreen->hasStartedCounting())
endScreen->startCountDown();
break;
}
void Game::handleKeyDown(SDL_Event &event) {
if (gameState == GameState::START_SCREEN) {
startScreen->handleEvent(event);
return;
} else if (gameState == GameState::END_SCREEN) {
if (event.type == SDL_KEYDOWN && !endScreen->hasStartedCounting())
endScreen->startCountDown();
return;
}
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;
}
return true;
}
void Game::handleGameEvent(SDL_Event &event) {
if (event.type == SDL_KEYDOWN) {
switch (event.key.keysym.sym) {
case SDLK_w:
leftPaddle->startMoving(true);
break;
case SDLK_s:
leftPaddle->startMoving(false);
break;
void Game::handleKeyUp(SDL_Event &event) {
if (gameState != GameState::GAME)
return;
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;
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;
}
case SDLK_UP:
rightPaddle->stopMoving(true);
break;
case SDLK_DOWN:
rightPaddle->stopMoving(false);
break;
}
}

View File

@ -36,7 +36,7 @@ public:
void update() override;
bool handleEvents() override;
void handleKeyUp(SDL_Event &event) override;
void handleGameEvent(SDL_Event &event);
void handleKeyDown(SDL_Event &event) override;
};

View File

@ -53,6 +53,25 @@ SdlWrapper::~SdlWrapper() {
SDL_Quit();
}
bool SdlWrapper::handleEvents() {
SDL_Event event;
while (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_QUIT:
return false;
case SDL_KEYDOWN:
handleKeyDown(event);
break;
case SDL_KEYUP:
handleKeyUp(event);
break;
}
}
return true;
}
int SdlWrapper::loop() {
while (running) {
if (!handleEvents())

View File

@ -30,5 +30,11 @@ protected:
virtual void update() = 0;
virtual bool handleEvents() = 0;
virtual void handleKeyUp(SDL_Event &event) = 0;
virtual void handleKeyDown(SDL_Event &event) = 0;
private:
bool handleEvents();
};