Search code examples
c#arrayscollision-detection

1D array collision


I'm struggling with a collision detection type method for a 1D array.

I have a console game with up to 4 players, each player rolls a dice in turn and makes a move on the board.

The rule is that there can only be one player on the board at the same time.

So if player one rolls a 1 he is on square one. If player 2 rolls a 1 on his turn he is on square two. If player 3 rolls a 1 on his turn then he is on square three. And so on...

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;
        }
}

This is my current method for moving the player, this is a test method at the minute demonstrating that that the players are each able to make a move. The result of this is that each player lands on square number 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;
    }

}

This is the method that is giving me a headache. I've been experimenting with the conditional and had it half working but just can't seem to get it right.

Many thanks in advance.


Solution

  • Assuming playerPositions[] is an array of integers which contains the number of the square that player is on, you can try:

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

    A less Linq-y solution (which amounts to the same thing) would be:

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