Pizzaguru
Pizzaguru

Reputation: 104

Sub class requires info of property in base class

Here is the code that shows what I try to accomplish.

public partial class Form1 : Form
{
    public List<Player> Players { get; set; }

    public Form1()
    {
        InitializeComponent();

        Players = new List<Player>();
        Players.Add(new Player() { ID = "Hero", Stack = 1000 });
        Players.Add(new Player() { ID = "Villain", Stack = 500 });

        MessageBox.Show(Players[0].Chipleader.ToString());
    }
}

public class Player
{
    public string ID { get; set; }
    public int Stack { get; set; }
    public bool Chipleader
    {
        get
        {
            // Dependent on the stacks of the other players
            return Stack == Players.Max(S => S.Stack);
        }
    }
}

I want every Player object to have a property "Chipleader" indicating true if the that player has the biggest stack. The player object needs properties of the other players (list of players in base class) to be able to do this. The reason I need this property to be in the Player class is because I'm using ObjectListView to list my player objects in a listview. I hope someone can show me a simple/logical way to do this.

Upvotes: 1

Views: 158

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564403

Typically, your "game" would manage which player is in the lead, not the other players. It's typically a bad design to have a class require knowledge of other classes in order to function correctly.

I would, instead, suggest having your "game" (the form) contain a Chipleader property that returned the player in the lead, ie:

public Player Chipleader
{
    get { return Players.OrderByDescending(s => s.Stack).FirstOrDefault(); }
} 

If you truly need this on Player, make a method, like so:

public bool IsChipLeader(Form1 game)
{
    // Maybe include check that "this" is part of the game...
    return this.Stack == game.Players.Max(s => s.Stack);
}

(I'd also recommend moving the Game logic into it's own "Game" class, and encapsulate that in the form, instead of having the game logic in Form1)

Upvotes: 5

Related Questions