Remove the game logic from InputManager

This commit is contained in:
2025-12-06 18:38:36 +08:00
parent ecbf7dad90
commit 995c01bd8c
3 changed files with 22 additions and 46 deletions

View File

@@ -1,6 +1,6 @@
#include "InputManager.h"
SDL_AppResult InputManager::handleInputEvent(const SDL_Event* event, const Renderer* g_renderer, Game* g_game) {
SDL_AppResult InputManager::handleInputEvent(const SDL_Event* event) {
switch (event->type) {
// 如果检测到退出
@@ -8,46 +8,16 @@ SDL_AppResult InputManager::handleInputEvent(const SDL_Event* event, const Rende
return SDL_APP_SUCCESS;
case SDL_EVENT_MOUSE_BUTTON_DOWN:
if (event->button.button == SDL_BUTTON_LEFT) {
// 将窗口坐标转为逻辑坐标
float logicalX, logicalY;
SDL_RenderCoordinatesFromWindow(
g_renderer->getSDLRenderer(),
static_cast<float>(event->button.x),
static_cast<float>(event->button.y),
&logicalX,
&logicalY
);
auto boardArea = g_renderer->getBoardArea();
auto click = handleMouseClick(static_cast<int>(logicalX), static_cast<int>(logicalY), boardArea);
if (click) {
auto [row, col] = click.value();
SDL_Log("click on (%d, %d)", row, col);
g_game->handleCoordinateInput(row, col);
g_game->printBoard();
} else {
SDL_Log("invail cilck aera!");
}
// 更新状态
m_currentInputState.mouseCilckOn = {event->button.x, event->button.y};
return SDL_APP_CONTINUE;
}
}
return SDL_APP_CONTINUE;
}
std::optional<std::pair<int, int>>
InputManager::handleMouseClick(int mouseX, int mouseY, const ui::BoardArea& area) {
// 判断是否点击在棋盘区域内
if (mouseX < area.x || mouseX >= area.x + area.cellSize * area.cols ||
mouseY < area.y || mouseY >= area.y + area.cellSize * area.rows) {
return std::nullopt; // 点击在棋盘外
}
// 转换为逻辑坐标
int col = (mouseX - area.x) / area.cellSize;
int row = (mouseY - area.y) / area.cellSize;
// 安全检查(通常不需要,但保险)
if (row >= 0 && row < area.rows && col >= 0 && col < area.cols) {
return std::pair<int, int>{row, col};
}
return std::nullopt;
}
InputState InputManager::GetInputState() const {
return m_currentInputState;
}

View File

@@ -1,14 +1,14 @@
#pragma once
#include <SDL3/SDL.h>
#include <optional>
#include <utility>
#include "ui/UIType.h"
class Renderer;
class Game;
#include "InputState.h"
class InputManager {
public:
SDL_AppResult handleInputEvent(const SDL_Event* event, const Renderer* g_renderer, Game* g_game);
// 调用前需传入当前棋盘渲染区域(来自 Renderer
std::optional<std::pair<int, int>> handleMouseClick(int mouseX, int mouseY, const ui::BoardArea& boardArea);
SDL_AppResult handleInputEvent(const SDL_Event* event);
InputState GetInputState() const;
private:
InputState m_currentInputState;
};

6
src/input/InputState.h Normal file
View File

@@ -0,0 +1,6 @@
#pragma once
#include <utility>
struct InputState
{
std::pair<float, float> mouseCilckOn;
};