firmfiasco firmfiasco - 9 days ago 7
C# Question

C# regarding enum methods

Hey everybody I'm new to C# and I'm having a few issues. I'm currently doing an assignment for school and I'm really stuck on this part. I've staring at it and googling things for hours and I'm having any luck. I have included below what I have so far.

The directions aren't that good.

"Create a public enum CharacterState for the 4 image states: Attacking, Defending, Idle, and Dead.
Now create a member variable state to hold the character state and a public property State with a get
and set. For now, fill in the default behavior of get and set to return/set the value of state."

Any help would be greatly appeciated! Thank you

namespace WPFBattle
{
class CharacterImage: System.Windows.Controls.Image
{
public enum Attacking{

}

public enum Defending{

}

public enum Idle{

}

public enum Dead{

}
public ImageSource IdleImageSource { get; set; }
public ImageSource AttackingImageSource { get; set; }
public ImageSource TakeDamageImageSource { get; set; }
public ImageSource DeadImageSource { get; set; }

protected void UpdateImageSource()
{
switch (State)
{
case CharacterState.Attacking:
this.Source = AttackingImageSource;
break;
case CharacterState.TakeDamage:
this.Source = TakeDamageImageSource;
break;
case CharacterState.Dead:
this.Source = DeadImageSource;
break;
case CharacterState.Idle:
default:
this.Source = IdleImageSource;
break;
}
}

protected override void OnRender(DrawingContext dc)
{
UpdateImageSource();
base.OnRender(dc);
}

public CharacterState State
{
get { return state; }
set
{
state = value;
this.Dispatcher.Invoke((Action)(() =>
{
UpdateImageSource();
}));
}
}
}
}

Answer

Starting with your enum.

Create a public enum CharacterState for the 4 image states: Attacking, Defending, Idle, and Dead ...

From your code, you have created a single enum for each state. Enums are useful for defining options, in your case, you are supposed to have an enum that defines the state of your character.

public enum CharacterState {
    Attacking,
    Defending,
    Idle,
    Dead
}

... Now create a member variable state to hold the character state and a public property State with a get and set.

public class Character {

    public Character()
    {
        State = CharacterState.Idle;
    }

    private CharacterState state; //-Member variable (private)

    public CharacterState State 
    {  get
       {
            return state; // note the casing in State and state
       }  
       set
       {
           State = value;
       }
}

Then you can access the current state of your character through its State property.

var character = new Character();
CharacterState state = character.State; // returns Idle.
// or set it
character.State = CharacterState.Attacking;
Console.WriteLine($"Take cover! character is {character.State}");
//- logs "Take cover! character is Attacking"

Hope this clarifies things.

Comments