gpt4 book ai didi

c# - 评估嵌套在 foreach 中的值和国际象棋中的 if 方法

转载 作者:行者123 更新时间:2023-11-30 14:44:49 25 4
gpt4 key购买 nike

我正在 Unity3D 中编写国际象棋游戏,我正在尝试编写方法来确定国王是否处于检查状态,方法是确定哪个国王是当前玩家要移动的国王,然后比较国王的位置与对手的威胁方 block 列表相对。

我试过使用 IndexOf , Intersect() ,以及其他一些东西,但我似乎无法使其正确匹配。如果我插入 Debug.LogConsole.Writeif() 内语句,国王的位置正确返回——但即使在 threatenedSquares 时它似乎也没有评估为真里面有国王的地位。

当前代码使用 threatedSquares 编辑,通过调试器返回值列表:

        public bool IsKingThreatened()
{
Vector2Int kingPosition;
GameObject[] kings;
kings = GameObject.FindGameObjectsWithTag("King");

foreach(GameObject king in kings)
{
if (currentPlayer.pieces.Contains(king))
{
kingPosition = GridForPiece(king);
Debug.Log("King position: " + kingPosition);
Debug.Log("Player: " + currentPlayer.name);
foreach(Vector2Int p in currentPlayer.threatenedSquares)
{
Debug.Log(p);
}

if (currentPlayer.threatenedSquares.Contains(kingPosition))
{
Debug.Log("King at " + kingPosition + "is threatened");
return true;
}
}
}
return false;
}

输出:

Debug.Log: King position:  (Correct coordinates)
Debug.Log: Player: (active player)

kingThreatened == false;

currentPlayer.pieces 是一个 List<GameObject>和threatedSquares 是一个 List<Vector2Int>

编辑:按照@clarkitech 的观点对其进行了一些清理;但是它仍然总是返回 false:

    public bool IsKingThreatened()
{
Vector2Int kingPosition;
GameObject[] kings;
kings = GameObject.FindGameObjectsWithTag("King");

foreach (GameObject king in kings)
{
if (currentPlayer.pieces.Contains(king))
{
kingPosition = GridForPiece(king);

return threatenedSquares.Contains(kingPosition);
}
}
return false;
}

最佳答案

你总是返回错误。这是问题区域的简化 View 。

    foreach (GameObject king in kings)
{
if (currentPlayer.pieces.Contains(king))
{
// your logic with no exit condition
}
}
return false;

一旦循环完成,它将总是返回false,除非您改为return kingThreatened

我会让这更直接一点,但我猜测了一些关于您的游戏部件的属性。

public bool isKingThreatened => currentPlayer.pieces
.Where(x => x.HasTag("king"))
.Where(x => threatenedSquares.Contains(GridForPiece))
.Any();

currentPlayer 拥有的棋子有标签 "king" 并且该棋子的位置在 threatenedSquares 集合中。

关于c# - 评估嵌套在 foreach 中的值和国际象棋中的 if 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57317738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com