Cogythea
Cogythea

Reputation: 93

Making a class only possess predefined states

I'm programming a rudimentary for an attacking submarine, and I want to have a variable which tells me which state the AI is in, e.g. Attacking, Retreating.

I know it's possible to use a string but I'm certain I've seen another way of doing it before, like Submarine.AIstate = AIstate.Attacking. Sorry if it seems like a basic question, but I'm pretty new to this kind of thing.

Any help will be appreciated :)

Upvotes: 1

Views: 86

Answers (3)

Saro Taşciyan
Saro Taşciyan

Reputation: 5236

I suppose what you want to achieve is using enum

public class Submarine
{
    public enum AIState
    {
        Attacking = 0,
        Retreating = 1
    }

    public AIState CurrentAIState { get; set; }

    // # Your fields, properties, constructor, methods here

    public void DecideNextMove()
    {
        if (CurrentAIState == AIState.Attacking)
        {
            // Decide
        }
        else if (CurrentAIState == AIState.Retreating)
        {
            // Decide
        }
    }
}

You may choose to use switch block instead of if else block as i did. And if you want to change current state of Submarine you can use property setter as CurrentState = AIState.Attacking

Upvotes: 1

Simon Whitehead
Simon Whitehead

Reputation: 65077

enums.

MSDN Link: http://msdn.microsoft.com/en-us/library/sbbt4032.aspx

Basically, you would have an enum that represents the state:

enum SubState {
    Idle = 0,
    Attacking,
    Retreating
}

Then you sub would have a property for the state:

class Submarine {
    public SubState State { get; set; }
}

Then you can set the state like this:

sub.State = SubState.Attacking;

..and check it like this:

switch (sub.State) {
    case SubState.Attacking:
         // do attacking stuff here
        break;
}

Upvotes: 2

geedubb
geedubb

Reputation: 4057

Create an enum with your states:

public enum AIState
{
   Attacking,
   Retreating
}

and a property on your Submarine class of that type:

public AIState AIState
{
  get; set;
}

Upvotes: 1

Related Questions