This is for a HW assignment, so it shouldn't be very difficult. In any case, we are supposed to create a base class of a Weapon and then child classes of MeleeWeapon ,Spell, Projectile, each with additional weapon attributes. That part is not so difficult. I am getting stuck with the following:
"Create a class that represents a Player with a Name and a Weapon"
I can manage creating a player class, but I'm not sure how to account for the weapon.
Do I have three different player classes such as public class Player : Spell: Weapon or public class Player: MeleeWeapon : Weapon? I feel like there should be a way to have one player class, but I'm getting flustered with how to do that. The player class also needs a constructor; again this isn't too hard, but I don't know how to account for the choices in weapon type unless I have more than one player class.
Basically, it seems like I want to have one grand child class (Player) -> three possible child classes (MeleeWeapon, Spell, Projectile) -> one parent class (Weapon), but I'm confusing myself here.
You're entirely mis-reading the requirement. Take a closer look:
Create a class that represents a Player with a Name and a Weapon
It's not saying that a Player is a Name and a Weapon, it's saying that a Player has a Name and a Weapon.
The Player
class should have two properties: Name
and Weapon
. This has nothing to do with inheritance.
You are confused. Take a step back and follow the instructions:
Create a class that represents a Player...
public class Player {}
...with a Name...
public class Player
{
public string Name { get; set; }
}
...and a Weapon.
public class Player
{
public string Name { get; set; }
public Weapon EquippedWeapon { get; set; }
}
You can now create different players with different weapons:
var alice = new Player { Name = "Alice", EquippedWeapon = new MeleeWeapon() };
var bob = new Player { Name = "Bob", EquippedWeapon = new Spell() };
The assignment asks you to use a has-a relationship between player and weapon instead of is-a
So in your Player class you will have
class Player
{
public string Name {get; protected set;}
public Weapon CurrentWeapon {get; protected set;}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.