I'm trying to create a program within which the user interacts with a virtual pet. This pet has attributes such as hunger, which is just stored as an integer between 1-10. Is there a way to decrease the value of said variable based on how much time has passed (since the pet was last fed, let's say)?
Hopefully i can use it to create a function like this:
static void hungerDecrease(CPet pet)
{
bool needsFeeding = false;
// some method of checking if say 4 hours has passed and if so set needsFeeding to be true
if (needsFeeding == true)
{
pet.Hunger -= 1;
}
}
The class CPet looks like this:
public class CPet
{
public string Name;
public string Gender;
// Attributes belonging to pets, with values being defined upon creation.
public int Hunger = 5;
public int Boredom = 5;
public int Happiness = 5;
public int Intelligence = 1;
public CPet(string name, string gender)
{
Name = name;
Gender = gender;
}
}
public class CPet
{
public string Name;
public DateTime LastFed;
...
}
static void hungerDecrease(CPet pet)
{
if (DateTime.Now > pet.LastFed.AddHours(4))
{
pet.Hunger -= 1;
pet.LastFed = DateTime.Now;
}
}
Related
This question already has answers here:
Unsure about parameters when calling base constructor from derived class
(2 answers)
Closed 2 years ago.
I'm creating a .NET core menu-based console app that allows you to add and manage players from different sports.
My Player class:
abstract class Player
{
enum PlayerType
{
HockeyPlayer,
BacketballPlayer,
BaseballPlayer
}
public abstract void Points();
private long playerId;
private string playerName;
private string teamName;
private int gamesPlayed;
public long PlayerId
{
get { return playerId; }
set { playerId = value; }
}
public string PlayerName
{
get { return playerName; }
set { playerName = value; }
}
public string TeamName
{
get { return teamName; }
set { teamName = value; }
}
public int GamesPlayed
{
get { return gamesPlayed; }
set { gamesPlayed = value; }
}
}
class HockeyPlayer : Player
{
private int assists;
private int goals;
public override void Points()
{
int totalPoints = assists + (2 * goals);
}
public int Assists
{
get { return assists; }
set { assists = value; }
}
public int Goals
{
get { return goals; }
set { goals = value; }
}
}
class BasketballPlayer : Player
{
private int fieldGoals;
private int threePointers;
public override void Points()
{
int totalPoints = (fieldGoals - threePointers) + (2 * threePointers);
}
public int FieldGoals
{
get { return fieldGoals; }
set { fieldGoals = value; }
}
public int ThreePointer
{
get { return threePointers; }
set { threePointers = value; }
}
}
class BaseballPlayer : Player
{
private int runs;
private int homeRuns;
public override void Points()
{
int totalPoints = (runs - homeRuns) + (2 * homeRuns);
}
public int Runs
{
get { return runs; }
set { runs = value; }
}
}
And a snippet of my main class:
class Controller
{
static void Main(string[] args)
{
List<Player> players = new List<Player>()
{
new HockeyPlayer(1, "Mitch Marner", "Toronto Maple Leafs", 5)
};
In the controller I am trying to populate the list with some sample data, but obviously I don't have a constructor in my derived HockeyPlayer class. How do I create a constructor for HockeyPlayer where the arguments are 'playerId', 'playerName', 'teamName', and 'gamesPlayed' which come from the parent class. I feel like I'm missing something very simple here.
A funny thing is that you are using 'object initialization' for the list, but trying to call the constructor of HockeyPlayer, where you also could use the object initialization method.
The object initialization is executed after the constructor (assigning properties) but enables construction and property initialization in one single statement
For example:
List<Player> players = new List<Player>()
{
new HockeyPlayer(1, "Mitch Marner", "Toronto Maple Leafs", 5);
};
List<Player> players = new List<Player>()
{
new HockeyPlayer
{
PlayerId = 1,
PlayerName = "Mitch Marner",
TeamName = "Toronto Maple Leafs",
GamesPlayed = 5
}
};
Constructors are usefull when certain parameters are mandatory. This way you force an initial value for a field/property.
Object initializers is just syntactic sugar for constructing and assigning properties. With a big difference (like i said) an object initializer can be treated as a single statement. (therefor you can pass it as an argument to a function.)
var player = new HockeyPlayer
{
PlayerId = 1,
PlayerName = "Mitch Marner",
TeamName = "Toronto Maple Leafs",
GamesPlayed = 5
}
VS
var player = new HockeyPlayer();
player.PlayerId = 1;
player.PlayerName = "Mitch Marner";
player.TeamName = "Toronto Maple Leafs";
player.GamesPlayed = 5;
public void sortByType(){}
what should i enter here if i have three types of customers different in the way they pay
I have a class customer that inhereted 3 other classes they have a name ,id ,balance and a name of the books array and the date of barrowing and returning how can i sort them by
types??
class Book
{
public string BName { get;set; }
public string Day { get;set; }
public string Month { get;set;} }
public string Year { get;set;} }
public override string ToString(){}
}
then I created an abstract class Customer
abstract class Customer
{
protected string name;
protected double balance;
protected double ID_num;
protected Book[] rental_books = new Book[3];
public string Name { get { return name; } set { name = value; } }
public double Balance { get { return balance; } set { balance = value; } }
public double ID_NUM { get { return ID_num; } set { ID_num = value; } }
public override string ToString() {}
public abstract void BarrowBook(string bn, string d, string m, string y);
public abstract void ReturnBook(string bn, string d, string m, string y);
public abstract void AddToBalance(double sum);
}
and inherted it to the other three child classes and add what I need to each method
class NormalCustomer : Customer{}
class MemberCustomer : Customer{}
class StudentCustomer : Customer{}
then I created a library class
class Library
{
private Customer[] customers;
private int MaxCust=0;
private int count = 0;
public Library(int MaxCust) { this.MaxCust = MaxCust; }
public void Add(Customer c) { customers[count++] = c; }
public void ToString() {
public void SortByBalance()
{
double hold;
for (int i = 0; i < customers.Length - 1; i++)
for (int k = 0; k < (customers.Length - 1) - i; k++)
{
if (customers[k].Balance > customers[k + 1].Balance)
{
hold = customers[k].Balance;
customers[k].Balance = customers[k + 1].Balance;
customers[k + 1].Balance = hold;
}
}
}
}
so all i need now is the methode i mentioned above and how to creat it
let's take your classes
public class Customer { ... }
public class NormalCustomer : Customer{}
public class MemberCustomer : Customer{}
public class StudentCustomer : Customer{}
Providing an array which contains all the children in a mixed order:
Customer [] array = new Customer[]
{
new StudentCustomer(),
new MemberCustomer(),
new NormalCustomer(),
new MemberCustomer(),
new StudentCustomer(),
new StudentCustomer(),
new NormalCustomer(),
};
You can use the method: OfType to extract the individual types:
var children_1 = array.OfType<NormalCustomer>();
var children_2 = array.OfType<MemberCustomer>();
var children_3 = array.OfType<StudentCustomer>();
Now you simply need to concatenate them into a single collection using the Concat method. It expects that the second collection contains the same type of elements so you need to cast it temporarily to the parent type:
Customer [] sorted children_1.Cast<Customer>().Concat(children_2).Concat(children_3).ToArray();
I have a class Father and an inherited class Child. Inside the Child's constructor I want to pass a Father class to cast all Father's properties.
This is my code
class Father
{
int prop1;
int prop2;
// many more properties;
}
class Child : Father
{
string _name;
int _age;
//etc...
public Child(string Name, int Age, Father father)
{
this._name = Name;
this._age = Age;
base = father; //<== this is what I mean to do
}
I know I can't do this directly. What is the right way?
This is complete code, some code is in spanish
class AuditRegistry : Audit
{
protected string _cud;
protected int _employee, _consecutive;
protected DateTime _date;
public string CUD { get { return _cud; } }
private int Consecutive { get { return _consecutive; } }
public DateTime Date { get { return _date; } }
public int Client { get; set; }
public int Employee { get { return _employee; } }
public float NetAmount
{
get
{
float acum = 0;
//Sum (qty * price) of products in a struct collection
}
}
public float GrossAmount
{
get
{
float acum = 0;
//Sum in acum (qty * price + tax) of each products in a struct collection
return acum;
}
}
public float Paid
{
get
{
float acum = 0;
//Sum every paid in a struct collection
return acum;
}
}
public float Change
{ get; set; }
public bool FullPaid
{
get { return (Paid != null && Paid >= NetAmount); }
}
public ArticlesCollection Products { get; set; } //struct previusly declared
public PaidsCollection Paids { get; set; } // struct previously declared
public AuditRegistry(string CUD, int Employee, int Consecutive, DateTime Date, int Client, int C, int Company, int Terminal )
{
this._cud = CUD;
this._employee = Employee;
this._consecutive = Consecutive;
this._date = Date;
this.Client = Client;
base._c = C;
base._company = Company;
base._terminal = Terminal;
}
}
class Order : AuditRegistry
{
int _consec;
public DateTime DeliveryDate { get; set; }
public int Consecutive { get { return _consec; } }
public char Modification { get; set; }
public string Code { get { return (_consec.ToString() + Modificacion); } }
public bool Entregado { get; set; }
/// <summary>
/// Constructor for load a Order from database to memory
/// </summary>
public Order(DateTime DeliveryDate, int Consecutive, char Modification, AuditRegistry Registry) // Here is the child constructor
{
this.DeliveryDate = DeliveryDate;
this._consec = Consecutive;
this.Modification = Modification;
base = AuditRegistry; //Wrong idea
}
/// <summary>
/// Constructor for new Order
/// </summary>
public Pedido(DateTime DeliveryDate, int Employee)
{
this.DeliveryDate = DeliveryDate;
this._consec = 1;
this.Modification = 'A';
base._employee = Employee;
base._date = DateTime.Now;
}
}
Semantics of a child being a father aside...
A good way is using a copy constructor:
class Father
{
int prop1;
int prop2;
// much more properties;
protected Father(Father copy)
{
prop1 = copy.prop1;
prop2 = copy.prop2;
}
}
class Child : Father
{
string _name;
int _age;
//etc...
public Child(string Name, int Age, Father father)
: base(father)
{
this._name = Name;
this._age = Age;
}
}
Its a protected constructor so only children of the parent class can call it. You use the constructor chaining base(father) to intantiate the construtor of the base class and pass the object you want to copy.
You can't assign the base object directly in code, its just a reference to the instance of the base class that the current class derives from.
There is absolutely no way to do this. A Child is a Father and you can't just swap part of the object out to another reference. The base keyword is only intended for calling base class methods explicitly.
Given that a Child is not a "type of" Father, inheritance is probably the wrong answer here anyways. You would be better off doing something like:
class Person
class Father : Person
class Child : Person
{
Father father;
}
(Pseudo-code above). Basically, prefer composition over inheritance here.
A simple program using properties to encapsulate.. Farmer has field snumberofCows andfeedMultiplier,
and write to console BagsOfFeed= numberofCows* feedMultiplier
namespace numberOfCows
{
class Farmer
{
private int bagsOfFeed;
//public const int FeedMultiplier = 30;
private int numberOfCows;
private int feedMultiplier;
//private int bagsOfFeed;
public Farmer(int numberOfCows, int feedMultiplie)
{
feedMultiplier = feedMultiplie;
//this.feedMultiplier = feedMultiplie;
NumberOfCows = numberOfCows;
//this.numberOfCows = numberOfCows;
}
public int FeedMultiplier { get { return feedMultiplier; } }
public int NumberOfCows
{
get
{
return numberOfCows;
}
set
{
numberOfCows = value;
//BagsOfFeed = numberOfCows * FeedMultiplier;
}
}
//READ ONLY PROPERTY
public int BagsOfFeed {
get { return bagsOfFeed; }
set { bagsOfFeed = NumberOfCows * FeedMultiplier; }
}
}
}
When call farmer = new Farmer( 15,30 ); Console.WriteLine("I need {0} bags of feed for {1} cows",farmer.BagsOfFeed, farmer.NumberOfCows); returns 0 BagsOfFeed...So I don't know where i goes wrong..[I thought properties is used to retrieve values which is to read sth out...also,,when should i use private set..]
The set method for BagsOfFeed is never called since you never do BagsOfFeed = something;, so the calculation is never done. You should probably have the calculation in the get method, and remove the field for it. Your class also has other fields that don't need to exist. For example, with the FeedMultiplier property, you can use private set; (this is called an auto-property) instead of having just a get with a backing field. It could be rewritten as:
class Farmer
{
public Farmer(int numberOfCows, int feedMultiplier)
{
this.FeedMultiplier = feedMultiplier;
this.NumberOfCows = numberOfCows;
}
public int FeedMultiplier { get; private set; }
public int NumberOfCows { get; set; }
public int BagsOfFeed {
get { return NumberOfCows * FeedMultiplier; }
}
}
This shows the correct result in your example:
I need 450 bags of feed for 15 cows
BagsOfFeed setter is never called (and shouldn't be, as it's calculated based of values of other properties). This property should look like that:
//READ ONLY PROPERTY
public int BagsOfFeed {
get { return NumberOfCows * FeedMultiplier; }
}
With that, private int bagsOfFeed; can be removed as it's unnecessary.
Is this a common way to store instances in a list that can be accessed by any class. Are there any better Techniques to achieving this?
class fish
{
string species = "Gold Fish";
int age = 1;
public static list<fish> Listholder = new list<fish>();
Listholder.add(this);
}
List<T> is not thread safe, so if you want to add/remove fishs from different threads you should use ConcurrentBag<T> instead.
For example:
public class Fish
{
public string Species { get; set; }
public int Age { get; set; }
private static System.Collections.Concurrent.ConcurrentBag<Fish> Aquarium = new System.Collections.Concurrent.ConcurrentBag<Fish>();
static Fish()
{
var goldFish = new Fish { Age = 1, Species = "Gold Fish" };
PutFishIntoAquarium(goldFish);
}
public static void PutFishIntoAquarium(Fish fish)
{
Aquarium.Add(fish);
}
public static void ClearAquarium()
{
Fish someFish;
while (!Aquarium.IsEmpty)
{
TryTakeFishOutOfAquarium(out someFish);
}
}
public static bool TryTakeFishOutOfAquarium(out Fish fish)
{
if (Aquarium.TryTake(out fish))
return true;
return false;
}
public static bool TryLookAtSomeFish(out Fish fish)
{
if (Aquarium.TryPeek(out fish))
return true;
return false;
}
}
I think what you're trying to get at is a way to store a globally accessible list of fish somewhere. I.e. to have a central repository of fish that all other classes get their fish from.
If this is so, there are other ways of doing this such as the Service/Repository pattern. Keep in mind that having a mutable public static field will make testing and re-usability harder.
a Class has Properties.
the class allows you to create objects.
class fish()
{
Private String _Type;
Private Int _Age;
Private String _Species;
Public Type
{
get _Type;
set _Type = Value;
}
Public Age
{
get _Age;
set _Age = Value;
}
Public Species
{
get _Species;
set _Species = Value;
}
public new(string Type, Int Age, String Species)
{
this.Type = Type;
this.Age = Age;
this.Species = Species;
}
}
//this is your new object.
Fish SunFish = New Fish("small", 9, "Sunfish");
after creating an object you can create a list of objects