UML class diagram: characters of a game

UML class diagram: Characters of a game


  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace GameCharacters
  5. {
  6.     abstract class Character                 // superclass
  7.     {
  8.         public abstract void show();         // has to be overriden by subclasses
  9.     }
  10.  
  11.     class Knight : Character                 // subclasses
  12.     {
  13.         public override void show()
  14.         {
  15.             Console.Out.WriteLine("I'm a noble knight.");
  16.         }
  17.     }
  18.     class Barbarian : Character
  19.     {
  20.         public override void show()
  21.         {
  22.             Console.Out.WriteLine("I'm a nasty barbarian.");
  23.         }
  24.     }
  25.     class Witch : Character
  26.     {
  27.         public override void show()
  28.         {
  29.             Console.Out.WriteLine("I'm a beautiful witch.");
  30.         }
  31.     }
  32.  
  33.     class Game
  34.     {
  35.  
  36.         static private List<Character> characters = new List<Character>();  // Array of superclass type
  37.  
  38.         static void Main(string[] args)
  39.         {
  40.             initialize();
  41.             play();
  42.         }
  43.  
  44.         static private void initialize()
  45.         {
  46.             Random rand = new Random();
  47.             int numCharacters = rand.Next(1, 6);            // 1 <= number of characters <= 5
  48.  
  49.             for (int i = 0; i < numCharacters; i++)
  50.             {
  51.                 switch (rand.Next(3))                       // late binding
  52.                 {              
  53.                     case 0:
  54.                         characters.Add(new Knight());
  55.                         break;
  56.                     case 1:
  57.                         characters.Add(new Barbarian());
  58.                         break;
  59.                     case 2:
  60.                         characters.Add(new Witch());
  61.                         break;
  62.                 }
  63.             }
  64.         }
  65.         static private void play()
  66.         {
  67.             foreach (Character character in characters)     // "Form" of objects is decided at runtime
  68.             {                                   
  69.                 character.show();                           // => POLYMORPHISM
  70.             }
  71.             Console.ReadKey();
  72.         }
  73.     }
  74. }
Last modified: Thursday, 22 August 2019, 9:59 AM