Lee Brindley
Lee Brindley

Reputation: 6482

c# 1D array collision detection

I've been tasked with creating a bard game using c# at university.

There is to be 2-4 players, each player rolls a dice in turn. The objective is to get to the last square on the grid.

The only relevant rule to this question is that no more than one player can be on the same square at once.

So for example

Both players start at position 0.

Player (A) rolls a 1 = Player(A) at square 1. Player (B) rolls a 1 = Player(B) 'skips' over Player(A) and lands on square 2.

I've left out the dice roll method and the main as to my knowledge they're not relevant to the question.

private static void PlayerTurn(int playerNo)
        {
        playerPositions[playerNo] = playerPositions[playerNo] + RollDice();  
        // The selected player rolls the dice and moves x amount of squares 
        //(dependant on dice roll value)
        }

That is the method for moving each player.

What I'm struggling with is the following method.

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

The method needs to check for collisions in the array. So if player (A) rolled a 1 on first roll and player (B) rolls a 1 on first roll i need to make player(B) 'leapfrog' player (A) to go to square 2.

AT the moment the game is just running in the console if that helps. Sorry about the format of this question, never asked on here before.

Many thanks

Upvotes: 1

Views: 761

Answers (1)

CSharpie
CSharpie

Reputation: 9467

Well you need to simply check if both players share the same position, and if that is the case the "active player" is allowed to move one more

if(playerpositions[otherPlayer] == playerpositions[currentPlayer])
    playerpositions[currentPlayer]++;

So if you need to make a function for that it would be:

static bool RocketInSquare(int squareNo)
{
    return playerpositions[0] == squareNo ||
           playerpositions[1] == squareNo ||
           playerpositions[2] == squareNo ||
           playerpositions[3] == squareNo;
}

And then

int dice = RollDice();

if(RocketInSquare(playerPositions[playerNo] + dice))
{
    playerPositions[playerNo] += dice +1;
}
else
{
    playerPositions[playerNo] += dice;
}

Upvotes: 1

Related Questions