3

我正在为一维数组的碰撞检测类型方法而苦苦挣扎。

我有一个最多 4 名玩家的控制台游戏,每个玩家轮流掷骰子并在棋盘上移动。

规则是棋盘上同时只能有一名玩家。

因此,如果玩家一掷出 1,他就在第一格。如果玩家 2 在他的回合中掷出 1,他就在第二格。如果玩家 3 在他的回合中掷出 1,那么他就在第三格。等等...

private static void PlayerMove(int playerNo)
{
    // TODO: Makes a move for the given player

        for (int i = 0; i < NumberOfPlayers; i++)
        {
            NextMove = playerPositions[i] + playerPositions[i] + DiceThrow();
            playerPositions[i] = NextMove;
        }
}

这是我目前移动玩家的方法,这是目前的一种测试方法,证明玩家每个人都能移动。这样做的结果是每个玩家都落在 1 号方格上。

static bool PlayerInSquare(int squareNo)
{
    //TODO: write a method that checks through the 
    //rocket positions and returns true if there is a rocket in the given square

    if (This conditional is what has me confused)
    {
        return true;
    }

}

这是让我头疼的方法。我一直在试验条件,并让它工作了一半,但似乎无法正确处理。

提前谢谢了。

4

2 回答 2

3

假设playerPositions[]是一个整数数组,其中包含玩家所在方格的编号,您可以尝试:

static bool PlayerInSquare(int squareNo)
{
    return playerPositions.Any(pos => pos == squareNo);
}

一个较少的 Linq-y 解决方案(相当于同一件事)将是:

static bool PlayerInSquare(int squareNo)
{
    for (int i = 0; i < NumberOfPlayers; i++)
        if (playerPositions[i] == squareNo)
            return true;

    return false;
}
于 2012-11-02T17:17:11.883 回答
1

看起来你可以使用:

static bool PlayerInSquare(int squareNo)
{
    return playerPositions.Any(pos => pos == squareNo);
}
于 2012-11-02T17:17:30.217 回答