Add CoordinateConverter to get logical postion

This commit is contained in:
2025-12-06 18:37:53 +08:00
parent dfa2fddd9d
commit ecbf7dad90
2 changed files with 53 additions and 0 deletions

View File

@@ -0,0 +1,38 @@
#include "CoordinateConverter.h"
CoordinateConverter::CoordinateConverter(SDL_Renderer* renderer) : m_renderer(renderer) {
}
CoordinateConverter::~CoordinateConverter() {
}
std::optional<std::pair<int, int>> CoordinateConverter::ScreenToBoard(float screenX, float screenY, BoardArea area) {
// 将窗口坐标转为逻辑坐标
float logicalX, logicalY;
SDL_RenderCoordinatesFromWindow(
m_renderer,
static_cast<float>(screenX),
static_cast<float>(screenY),
&logicalX,
&logicalY
);
int mouseX = static_cast<int>(logicalX);
int mouseY = static_cast<int>(logicalY);
// 判断是否点击在棋盘区域内
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;
}

View File

@@ -0,0 +1,15 @@
#pragma once
#include "utils/Config.h"
#include <SDL3/SDL.h>
#include <utility>
#include <optional>
class CoordinateConverter {
public:
CoordinateConverter(SDL_Renderer* renderer);
~CoordinateConverter();
// 将物理坐标转化成逻辑坐标
std::optional<std::pair<int, int>> ScreenToBoard(float screenX, float screenY, BoardArea aera);
private:
SDL_Renderer* m_renderer;
};