问题描述
我需要制作西洋双陆棋游戏。游戏已完成 90%。我必须做最后的游戏(当你从“家”拿出你的跳棋时,我不知道它是如何用英语称呼的)。我有 ArrayPieseAlbe 中的所有 whitecheckers,我正在使用 foreach 检查位置是否匹配。
public bool SuntToatePieseAlbeCasa()
{
foreach (PiesaAlba p in ArrayPieseAlbe)
{
return p.Location.X > 503; //503 is the right location
}
return false;
PiesaAlba 是白色跳棋所在的班级。 ArrayPieseAlbe 包含所有白色棋盘格。出于某种奇怪的原因,这不能正常工作。当“家”中有 7 个或更多跳棋时,它就可以工作,但需要所有 15 个跳棋都在那里才能正常工作。有什么建议吗?对不起我的英语不好
解决方法
如果 所有 的部分都是“家”,则您需要返回 true。目前,如果 任何(即至少一个)碎片在家里,您将返回 true。
要解决此问题,您的逻辑应该是:
- 遍历每个部分并检查它是否在家里
- 如果没有,立即返回false
- 如果所有部分都已检查,则返回 true
这看起来像:
public bool SuntToatePieseAlbeCasa()
{
foreach (PiesaAlba p in ArrayPieseAlbe)
{
if (p.Location.X <= 503) //503 is the right location
{
return false;
}
}
return true;
}
您也可以使用 System.Linq 中的 All()
方法:
public bool SuntToatePieseAlbeCasa()
{
return ArrayPieseAlbe.All(p => p.Location.X > 503);
}
看一下 source of All()
,它的作用与上面基本相同,但使用谓词在循环内部进行检查:
public static bool All<TSource>(this IEnumerable<TSource> source,Func<TSource,bool> predicate) {
if (source == null) throw Error.ArgumentNull("source");
if (predicate == null) throw Error.ArgumentNull("predicate");
foreach (TSource element in source) {
if (!predicate(element)) return false;
}
return true;
}