鉴于结构:
structure box_dimensions:
int? left
int? right
int? top
int? bottom
point? top_left
point? top_right
point? bottom_left
point? bottom_right
point? top_center
point? bottom_center
point? center_left
point? center_right
point? center
int? width
int? height
rectangle? bounds
可以定义每个字段的位置。
你将如何实现check_and_complete(box_dimensions)
功能?
您可以通过其中心,宽度和高度,或top_left和bottom_right角等来描述框
我能想到的唯一解决方案包含许多if-else的方法。我确信这是一种聪明的方法。
编辑
如果你想知道我最终是如何得到这样的结构,这就是为什么:
我正在研究“约束布局”系统的想法:
用户定义一堆框,并为每个框定义一组约束,如“box_a.top_left = box_b.bottom_right”,“box_a.width = box_b.width / 2”。
真实的结构字段实际上是表达式AST,而不是值。
因此,我需要检查一个框是否“欠约束”或“过度约束”,如果没有问题,请从给定框中创建缺少的表达式AST。
是的,当然会有太多的if-else
s。这是我试图让他们合理组织:
howManyLefts = 0
if (left is set) { realLeft = left; howManyLefts++; }
if (top_left is set) { realLeft = top_left.left; howManyLefts++; }
if (bottom_left is set) { realLeft = bottom_left.left; howManyLefts++; }
if (center_left is set) { realLeft = center_left.left; howManyLefts++; }
if (bounds is set) { realLeft = bounds.left; howManyLefts++; }
if (howManyLefts > 1) return error;
现在,重复center
,right
和width
的代码块。现在你最终得到howManyLefts
,howManyCenters
,howManyRights
和howManyWidths
,所有这些都是零或一,取决于是否提供了值。您需要设置两个值,两个未设置,因此:
if (howManyLefts + howManyRights + howManyCenters + howManyWidths != 2) return error
if (howManyWidths == 0)
{
// howManyWidths is 0, so we look for the remaining 0 and assume the rest is 1s
if (howManyCenters == 0)
{ realWidth = realRight - realLeft; realCenter = (realRight + realLeft) / 2; }
else if (howManyLefts == 0)
{ realWidth = 2 * (realRight - realCenter); realLeft = realRight - realWidth; }
else
{ realWidth = 2 * (realCenter - realLeft); realRight = realLeft + realWidth; }
}
else
{
// howManyWidths is 1, so we look for the remaining 1 and assume the rest is 0s
if (howManyCenters == 1)
{ realLeft = realCenter - realWidth / 2; realRight = realCenter + realWidth / 2; }
else if (howManyLefts == 1)
{ realRight = realLeft + realWidth; realCenter = (realRight + realLeft) / 2; }
else
{ realLeft = realRight - realWidth; realCenter = (realRight + realLeft) / 2; }
}
现在,重复垂直轴的所有内容(即用{left
,center
,right
,width
}替换{top
,center
,bottom
,height
}。