This repository has been archived by the owner on May 30, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DetectCell.ts
95 lines (80 loc) · 2.25 KB
/
DetectCell.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
interface IDetectCell {
detect(x: number, y: number): { row: number; column: number } | null;
}
class DetectCellConfig {
width: number;
height: number;
rowCount: number;
columnCount: number;
cellWidth: number;
constructor(
width: number,
height: number,
rowCount: number,
columnCount: number,
cellWidth: number
) {
this.width = width;
this.height = height;
this.rowCount = rowCount;
this.columnCount = columnCount;
this.cellWidth = cellWidth;
}
}
class DetectCellBuilder {
private config: DetectCellConfig;
constructor() {
this.config = new DetectCellConfig(0, 0, 0, 0, 0);
}
public withWidth(width: number): DetectCellBuilder {
this.config.width = width;
return this;
}
public withHeight(height: number): DetectCellBuilder {
this.config.height = height;
return this;
}
public withRowCount(rowCount: number): DetectCellBuilder {
this.config.rowCount = rowCount;
return this;
}
public withColumnCount(columnCount: number): DetectCellBuilder {
this.config.columnCount = columnCount;
return this;
}
public withCellWidth(cellWidth: number): DetectCellBuilder {
this.config.cellWidth = cellWidth;
return this;
}
public build(): IDetectCell {
return new DetectCell(this.config);
}
}
class DetectCell implements IDetectCell {
#config: DetectCellConfig;
constructor(config: DetectCellConfig) {
this.#config = config;
}
detect(x: number, y: number): { row: number; column: number } | null {
const centerX = this.#config.width / 2;
const centerY = this.#config.height / 2;
const topLeftX =
centerX - (this.#config.cellWidth * this.#config.columnCount) / 2;
const topLeftY =
centerY - (this.#config.cellWidth * this.#config.rowCount) / 2;
const translatedX = x - topLeftX;
const translatedY = y - topLeftY;
if (
translatedX < 0 ||
translatedY < 0 ||
translatedX >= this.#config.columnCount * this.#config.cellWidth ||
translatedY >= this.#config.rowCount * this.#config.cellWidth
)
return null;
return {
row: Math.trunc(translatedY / this.#config.cellWidth),
column: Math.trunc(translatedX / this.#config.cellWidth),
};
}
}
export { DetectCellBuilder };