patterncsharpMinor
Initial starting player
Viewed 0 times
startingplayerinitial
Problem
I'm making a game battle system, where there are 2 players.
I need to have in 2 variables who attacks first (
At the moment I have this code:
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.
- Every player can have multiple units to control, but only one at a time.
- Every unit has an
int curSpeedvariable;
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_1andplayer_2are instances ofPlayerClass
current, is a instance ofUnitClass, 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:
Another remark: properties are UpperCamelCase so this
should be
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.curSpeedshould be
player_1.Current.SpeedCode Snippets
player_1.current.curSpeedplayer_1.Current.SpeedContext
StackExchange Code Review Q#47723, answer score: 7
Revisions (0)
No revisions yet.