Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello everyone for a school project I am making a connect 4 game were 2 players can play. I am stuck however on how to switch each player's turn. I have used a variable int PlayerNo that can either be 1 or 2 (player 1 or player 2) and changing this value determines whether a green counter (2) or a red counter (1) drop down the board. I need to know how to alternate this value every turn and below is all the code where the variable is used. My code is quite messy at the minute so please forgive me and if you need clarification on anything please ask me.

What I have tried:

C#
private void SwapPlayer(int playerNumber)
        {
            if (playerNumber == 1)
            {
                playerNumber = 2;
            }

            else if (playerNumber == 2)
            {
                playerNumber = 1;
            }
        }
Posted
Updated 4-Apr-16 13:15pm
v3
Comments
Per Söderlund 5-Apr-16 8:58am    
It´s important that you understand the difference between value and reference type.
when you are passing an int (value type) as a parameter you are passing its value and you cannot change the variable you use when calling the SwapPlayer method.

If you change "private void SwapPlayer(int playerNumber)"
into "private void SwapPlayer(ref int playerNumber)"
you will pass in a reference to the variable and you can change it within the method.

Hope I didnt complicate things for you.

1 solution

You declare playerNo as a local variable in slotArray_DragDrop(..). When the method is done, it's forgotten and the next time it's initialized with 1 again...

And you pass it as a value parameter into SwapPlayer(..) so any change being done to it doesn't reflect to playerNo in slotArray_DragDrop(..)...
 
Share this answer
 
Comments
Member 12144313 4-Apr-16 18:24pm    
That worked thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900