axeefectushka

Untitled

Nov 11th, 2019
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.94 KB | None | 0 0
  1. using System;
  2.  
  3.  
  4. struct Key : IComparable
  5. {
  6.  
  7.     private readonly sbyte _key;
  8.  
  9.     public Key(Note note, Accidental accidental, Octave octave)
  10.     {
  11.         int noteNumber = ((int)note + 1) / 2;
  12.  
  13.         _key = (sbyte)(3 * noteNumber + (sbyte)accidental + 21 * (sbyte)octave);
  14.  
  15.         int keyNumber = ToTone();
  16.  
  17.         // Если представить что "С" 1-ой октавы - это ноль, тогда номер самой левой
  18.         // клавиши - это -39
  19.  
  20.         if (keyNumber < -39)
  21.         {
  22.             _key = -69;
  23.         }
  24.        
  25.         else if (keyNumber > 48)
  26.         {
  27.             _key = 84;
  28.         }
  29.  
  30.     }
  31.  
  32.     public bool Equals(Key other)
  33.     {
  34.         return ToTone() == other.ToTone();
  35.     }
  36.  
  37.     public override bool Equals(object obj)
  38.     {
  39.         return obj is Key key && Equals(key);
  40.     }
  41.  
  42.     public override int GetHashCode()
  43.     {
  44.         return ToTone();
  45.     }
  46.  
  47.     public override string ToString()
  48.     {
  49.         Note note = new[] { Note.C, Note.D, Note.E, Note.F, Note.G, Note.A, Note.H }[(_key + 85) % 21 / 3];
  50.  
  51.         switch ((Accidental)(((_key + 85) % 3) - 1))
  52.         {
  53.             case Accidental.Flat:
  54.                 return $"{note}b ({(Octave)((_key+ 85) / 21 - 4)})";
  55.  
  56.             case Accidental.Sharp:
  57.                 return $"{note}# ({(Octave)((_key + 85) / 21 - 4)})";
  58.  
  59.             default:
  60.                 return $"{note} ({(Octave)((_key + 85) / 21 - 4)})";
  61.         }
  62.     }
  63.  
  64.     public int CompareTo(object obj)
  65.     {
  66.         return obj is Key key ? ToTone() - key.ToTone() : -1;
  67.     }
  68.  
  69.     private int ToTone()
  70.     {
  71.         Octave octave = (Octave)((_key + 85) / 21 - 4);
  72.  
  73.         Note note = new[] { Note.C, Note.D, Note.E, Note.F, Note.G, Note.A, Note.H }[(_key + 85) % 21 / 3];
  74.  
  75.         Accidental accidental = (Accidental)((_key + 85) % 3 - 1);
  76.  
  77.         return (int)octave * 12 + (int)note + (int)accidental;
  78.     }
  79. }
Add Comment
Please, Sign In to add comment