HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Initial starting player

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
startingplayerinitial

Problem

I'm making a game battle system, where there are 2 players.

  • Every player can have multiple units to control, but only one at a time.



  • Every unit has an int curSpeed variable;



I need to have in 2 variables who attacks first (Player f) and who attacks second (Player s), based on the speed of the current controlling unit.

At the moment I have this code:

  • player_1 and player_2 are instances of Player Class



  • current, is a instance of Unit Class, it is the current controlling unit.



Player f = null; //Player attacking first
Player s = null; //Player attacking second

//Check the speed of the units, and determine who attack first
f = player_1.current.curSpeed > player_2.current.curSpeed ? player_1 : player_1.current.curSpeed < player_2.current.curSpeed ? player_2 : null;

//if f is null (units have the same speed)
if(f==null){
    //Randomize who goes first
    System.Random rnd = new System.Random();
    int rng = rnd.Next(0,2);
    f = rng == 0 ? player_1 : player_2;
    s = rng == 0 ? player_2 : player_1;
}else{
    s = f.id == player_1.id ? player_2 : player_1;
}


It is working, but I feel that this is confusing and the 'wrong way' to do it.

I need tips on how I can code this in a better way.

UPDATE:
New version of the code including all the suggestions can be found here.

Solution

Your code is indeed confusing, primarily because of the naming:

f should be firstPlayer, s should be secondPlayer and curSpeed should be speed or currentSpeed (it depends on whether there are other "speeds" to distinguish from).

Another remark: properties are UpperCamelCase so this

player_1.current.curSpeed


should be

player_1.Current.Speed

Code Snippets

player_1.current.curSpeed
player_1.Current.Speed

Context

StackExchange Code Review Q#47723, answer score: 7

Revisions (0)

No revisions yet.