Solution: Random creation of game characters
Completion requirements

UML class diagram: Characters of a game
- using System;
- using System.Collections.Generic;
- namespace GameCharacters
- {
- abstract class Character // superclass
- {
- public abstract void show(); // has to be overriden by subclasses
- }
- class Knight : Character // subclasses
- {
- public override void show()
- {
- Console.Out.WriteLine("I'm a noble knight.");
- }
- }
- class Barbarian : Character
- {
- public override void show()
- {
- Console.Out.WriteLine("I'm a nasty barbarian.");
- }
- }
- class Witch : Character
- {
- public override void show()
- {
- Console.Out.WriteLine("I'm a beautiful witch.");
- }
- }
- class Game
- {
- static private List<Character> characters = new List<Character>(); // Array of superclass type
- static void Main(string[] args)
- {
- initialize();
- play();
- }
- static private void initialize()
- {
- Random rand = new Random();
- int numCharacters = rand.Next(1, 6); // 1 <= number of characters <= 5
- for (int i = 0; i < numCharacters; i++)
- {
- switch (rand.Next(3)) // late binding
- {
- case 0:
- characters.Add(new Knight());
- break;
- case 1:
- characters.Add(new Barbarian());
- break;
- case 2:
- characters.Add(new Witch());
- break;
- }
- }
- }
- static private void play()
- {
- foreach (Character character in characters) // "Form" of objects is decided at runtime
- {
- character.show(); // => POLYMORPHISM
- }
- Console.ReadKey();
- }
- }
- }
Last modified: Thursday, 22 August 2019, 9:59 AM