Files
mahjong/components/hcm/hcmFun.swift
T
2026-11-13 13:24:23 +03:00

64 lines
1.9 KiB
Swift

private func hcmColumnCount(
width: Float,
height: Float
) -> Int {
#if os(iOS)
if height > width {
return 3
}
#endif
let reflowRatio: Float = 1.75
if width >= height * reflowRatio {
return 8
} else if height >= width * reflowRatio {
return 2
} else if height >= width * 1.5 {
return 3
}
return 4
}
func hcmResetItemPositions(_ uiSize: [Float]) -> [HCMItemPosition] {
let width = uiSize[0]
let height = uiSize[1]
guard width > 0, height > 0 else { return [] }
let columns = hcmColumnCount(width: width, height: height)
let itemCount = 16
let rows = (itemCount + columns - 1) / columns
let gap = min(25, width / Float(2 * (columns + 1)), height / Float(2 * (rows + 1)))
let edgeGap = 2 * gap
let horizontalGaps = Float(columns - 1) * gap
let verticalGaps = Float(rows - 1) * gap
let side = min(
(width - horizontalGaps - 2 * edgeGap) / Float(columns),
(height - verticalGaps - 2 * edgeGap) / Float(rows)
)
let top = -(Float(rows) * side + verticalGaps) / 2
return (0..<itemCount).map { index in
let column = index % columns
let row = index / columns
let tilesInRow = min(columns, itemCount - row * columns)
let rowWidth = Float(tilesInRow) * side + Float(tilesInRow - 1) * gap
return HCMItemPosition(
height: side,
width: side,
x: -rowWidth / 2 + Float(column) * (side + gap),
y: top + Float(row) * (side + gap)
)
}
}
func hcmItemId(
_ itemPositions: [HCMItemPosition],
_ position: [Float]
) -> Int {
let x = position[0]
let y = position[1]
let index = itemPositions.firstIndex { item in
x >= item.x && x < item.x + item.width &&
y >= item.y && y < item.y + item.height
}
return index ?? -1
}