The following example demonstrates the wording of the animal, which uses a constructor.
In the Main function, using the animal to create a cat, a dog.
Cats and dogs to attack each other until one dies.
code show as below:
class Animal { public String name; // animal name public int HP, Attack, Speed; // animal blood, attack, attack speed public Animal ( String n-, int Life, int Force, int S) { name = n-; HP = Life; Attack = Force; Speed = S; } public void Attack (Animal X) { x.hp-= attack*speed; } public void show_Me() { Console.WriteLine(name+"还剩"+hp.ToString()+"点血"); } } class Program { static void Main(string[] args) { Animal a, b; a = new Animal("dogy", 100, 20, 1); b = new Animal("caty", 80, 15, 2); do { a.Attack(b); b.show_Me(); b.Attack(a); a.show_Me(); } while (a.hp >= 0 && b.hp >= 0); Console.ReadKey(); } }
running result:
Of course, it can also be used to make the results appear random function variables.