Simon dice: "Hazme un juego bonito" -- # campo con wpf campo con community-challenge campo con async-await campo con simon-says camp codereview Relacionados El problema

Simon Says: “Make me a pretty game”


44
vote

problema

Español

en Memoriam

Ralph H. Baer, ​​co-inventor del juego original "Simon", murió sábado 6 de diciembre th 2014, a 92 < / a>. Con su paso, este pequeño desafío amistoso se convirtió inadvertidamente en un memorial para el padre de las consolas de videojuegos. Descansa en paz, señor Baer, ​​has cambiado nuestras vidas para siempre.


Finalmente recibí mi Simon dice Implementación para trabajar como pretendía Para. Eso es genial, pero ahora me queda con un desastre y no estoy seguro de dónde comenzar a limpiar (código completo en github ).

según las especificaciones, hubo 4 botones. Así que creé un enum y lo llamo SimonButton :

  public enum SimonButton {     Green,     Red,     Blue,     Yellow }   

He creado una clase SimonSaysRound que implementa INotifyPropertyChanged , para enlazar con la interfaz de usuario, en su mayoría para proporcionar la puntuación del jugador.

  public class SimonSaysRound : INotifyPropertyChanged {     private const int PointsForGoodMatch = 5;      private readonly SimonButton[] _sequence;     private int _matches;     private int _score;      public SimonSaysRound(IEnumerable<SimonButton> sequence, int score)     {         _sequence = sequence.ToArray();         _score = score;         _matches = 0;     }      public event EventHandler<SimonSaysScoreEventArgs> RoundCompleted;     public void OnRoundCompleted()     {         var handler = RoundCompleted;         if (handler != null)         {             var result = _matches == _sequence.Length;             RoundCompleted(this, new SimonSaysScoreEventArgs(result, Score));         }     }      public void Play(SimonButton button)     {         var success = _sequence[_matches] == button;         if (success)         {             Score += PointsForGoodMatch;             _matches++;         }          if (!success || _matches == _sequence.Length)         {             OnRoundCompleted();         }     }      public int Round     {         get { return _sequence.Length; }     }      public int Score     {         get { return _score; }         private set         {             if (value == _score) return;             _score = value;             OnPropertyChanged();         }     }      public int Length { get { return _sequence.Length; } }     public IEnumerable<SimonButton> Sequence { get { return _sequence; } }      public event PropertyChangedEventHandler PropertyChanged;      [NotifyPropertyChangedInvocator]     protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)     {         PropertyChangedEventHandler handler = PropertyChanged;         if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));     } }   

Normalmente no implemento mi using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace NewCalculator { public partial class MainWindow : Window { static int[] numbersArray = new int[10]; static string[] operatorsArray = new string[9]; static string storageVariable; static int numbersCounter = 0; static int operatorsCounter = 0; static int total = 0; static bool totalled = false; public MainWindow() { InitializeComponent(); } private void One_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "1"; storageVariable += "1"; } private void Two_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "2"; storageVariable += "2"; } private void Three_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "3"; storageVariable += "3"; } private void Four_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "4"; storageVariable += "4"; } private void Five_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "5"; storageVariable += "5"; } private void Six_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "6"; storageVariable += "6"; } private void Seven_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "7"; storageVariable += "7"; } private void Eight_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "8"; storageVariable += "8"; } private void Nine_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "9"; storageVariable += "9"; } private void Zero_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "0"; storageVariable += "0"; } private void Add_Click(object sender, RoutedEventArgs e) { setNumber(storageVariable); setOperator("+"); Display.Content += "+"; } private void Subtract_Click(object sender, RoutedEventArgs e) { setNumber(storageVariable); setOperator("-"); Display.Content += "-"; } private void Multiply_Click(object sender, RoutedEventArgs e) { setNumber(storageVariable); setOperator("*"); Display.Content += "x"; } private void Divide_Click(object sender, RoutedEventArgs e) { setNumber(storageVariable); setOperator("/"); Display.Content += "/"; } private void Equal_Click(object sender, RoutedEventArgs e) { setNumber(storageVariable); for (int i = 0; i < operatorsCounter; i++) { if (operatorsArray[i] == "+" && i == 0) { total = numbersArray[i] + numbersArray[i + 1]; } else if (operatorsArray[i] == "+") { total = total + numbersArray[i + 1]; } else if (operatorsArray[i] == "-" && i == 0) { total = numbersArray[i] - numbersArray[i + 1]; } else if (operatorsArray[i] == "-") { total = total - numbersArray[i + 1]; } else if (operatorsArray[i] == "*" && i == 0) { total = numbersArray[i] * numbersArray[i + 1]; } else if (operatorsArray[i] == "*") { total = total * numbersArray[i + 1]; } else if (operatorsArray[i] == "/" && i == 0) { total = numbersArray[i] / numbersArray[i + 1]; } else if (operatorsArray[i] == "/") { total = total / numbersArray[i + 1]; } } Display.Content = total; numbersArray = null; operatorsArray = null; storageVariable = null; numbersCounter = 0; operatorsCounter = 0; total = 0; totalled = true; } static void setNumber(String Number) { numbersArray[numbersCounter] = Convert.ToInt16(Number); storageVariable = null; numbersCounter++; } static void setOperator(String Op) { operatorsArray[operatorsCounter] = Op; operatorsCounter++; } private void AC_Click(object sender, RoutedEventArgs e) { Display.Content = ""; numbersArray = null; operatorsArray = null; storageVariable = null; numbersCounter = 0; operatorsCounter = 0; total = 0; } } } 0 como este: RESHARPER sugirió algo, y quería ver lo que hizo .. y no me disgustan.

Cuando se inicia la aplicación, se muestra la ventana principal, y una animación revela un botón "Inicio":

¡Inicio!

Cuando se hace clic en el botón, la barra de mensajes se colapsa, y un botón destella rápidamente animando rápidamente el valor de compensación de un gradiente radial (con efectos de sonido que acompañan):

azul cuadrante encendido

Cuando el jugador ingresa a la secuencia correcta, la barra intermedia se expande revela un mensaje "completado redondo" que muestra al jugador su puntaje; El juego se reanuda cuando el jugador hace clic / colapsa el mensaje:

Ronda 1 completada! Listo?

La pantalla "Game Over" muestra la puntuación del jugador y la cantidad de rondas completadas; Al hacer clic en el mensaje, cierra la ventana, y luego el programa finaliza:

oops! 6 rondas completadas. Su puntuación: 115

El XAML / UI es revisable aquí ; Esta publicación se trata del código de aplicación real:

  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes;  namespace NewCalculator {     public partial class MainWindow : Window     {         static int[] numbersArray = new int[10];         static string[] operatorsArray = new string[9];          static string storageVariable;         static int numbersCounter = 0;         static int operatorsCounter = 0;         static int total = 0;         static bool totalled = false;          public MainWindow()         {             InitializeComponent();         }          private void One_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "1";             storageVariable += "1";         }         private void Two_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "2";             storageVariable += "2";         }         private void Three_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "3";             storageVariable += "3";         }         private void Four_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "4";             storageVariable += "4";         }         private void Five_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "5";             storageVariable += "5";         }         private void Six_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "6";             storageVariable += "6";         }         private void Seven_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "7";             storageVariable += "7";         }         private void Eight_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "8";             storageVariable += "8";         }         private void Nine_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "9";             storageVariable += "9";         }         private void Zero_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "0";             storageVariable += "0";         }         private void Add_Click(object sender, RoutedEventArgs e)         {             setNumber(storageVariable);             setOperator("+");             Display.Content += "+";         }         private void Subtract_Click(object sender, RoutedEventArgs e)         {             setNumber(storageVariable);             setOperator("-");             Display.Content += "-";         }         private void Multiply_Click(object sender, RoutedEventArgs e)         {             setNumber(storageVariable);             setOperator("*");             Display.Content += "x";         }         private void Divide_Click(object sender, RoutedEventArgs e)         {             setNumber(storageVariable);             setOperator("/");             Display.Content += "/";         }         private void Equal_Click(object sender, RoutedEventArgs e)         {             setNumber(storageVariable);             for (int i = 0; i < operatorsCounter; i++)             {                 if (operatorsArray[i] == "+" && i == 0)                 {                     total = numbersArray[i] + numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "+")                 {                     total = total + numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "-" && i == 0)                 {                     total = numbersArray[i] - numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "-")                 {                     total = total - numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "*" && i == 0)                 {                     total = numbersArray[i] * numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "*")                 {                     total = total * numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "/" && i == 0)                 {                     total = numbersArray[i] / numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "/")                 {                     total = total / numbersArray[i + 1];                 }             }             Display.Content = total;             numbersArray = null;             operatorsArray = null;             storageVariable = null;             numbersCounter = 0;             operatorsCounter = 0;             total = 0;             totalled = true;         }         static void setNumber(String Number)         {             numbersArray[numbersCounter] = Convert.ToInt16(Number);             storageVariable = null;             numbersCounter++;         }         static void setOperator(String Op)         {             operatorsArray[operatorsCounter] = Op;             operatorsCounter++;         }         private void AC_Click(object sender, RoutedEventArgs e)         {             Display.Content = "";             numbersArray = null;             operatorsArray = null;             storageVariable = null;             numbersCounter = 0;             operatorsCounter = 0;             total = 0;         }     } } 1  

y el código de atrás para la ventana principal:

  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes;  namespace NewCalculator {     public partial class MainWindow : Window     {         static int[] numbersArray = new int[10];         static string[] operatorsArray = new string[9];          static string storageVariable;         static int numbersCounter = 0;         static int operatorsCounter = 0;         static int total = 0;         static bool totalled = false;          public MainWindow()         {             InitializeComponent();         }          private void One_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "1";             storageVariable += "1";         }         private void Two_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "2";             storageVariable += "2";         }         private void Three_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "3";             storageVariable += "3";         }         private void Four_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "4";             storageVariable += "4";         }         private void Five_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "5";             storageVariable += "5";         }         private void Six_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "6";             storageVariable += "6";         }         private void Seven_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "7";             storageVariable += "7";         }         private void Eight_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "8";             storageVariable += "8";         }         private void Nine_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "9";             storageVariable += "9";         }         private void Zero_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "0";             storageVariable += "0";         }         private void Add_Click(object sender, RoutedEventArgs e)         {             setNumber(storageVariable);             setOperator("+");             Display.Content += "+";         }         private void Subtract_Click(object sender, RoutedEventArgs e)         {             setNumber(storageVariable);             setOperator("-");             Display.Content += "-";         }         private void Multiply_Click(object sender, RoutedEventArgs e)         {             setNumber(storageVariable);             setOperator("*");             Display.Content += "x";         }         private void Divide_Click(object sender, RoutedEventArgs e)         {             setNumber(storageVariable);             setOperator("/");             Display.Content += "/";         }         private void Equal_Click(object sender, RoutedEventArgs e)         {             setNumber(storageVariable);             for (int i = 0; i < operatorsCounter; i++)             {                 if (operatorsArray[i] == "+" && i == 0)                 {                     total = numbersArray[i] + numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "+")                 {                     total = total + numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "-" && i == 0)                 {                     total = numbersArray[i] - numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "-")                 {                     total = total - numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "*" && i == 0)                 {                     total = numbersArray[i] * numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "*")                 {                     total = total * numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "/" && i == 0)                 {                     total = numbersArray[i] / numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "/")                 {                     total = total / numbersArray[i + 1];                 }             }             Display.Content = total;             numbersArray = null;             operatorsArray = null;             storageVariable = null;             numbersCounter = 0;             operatorsCounter = 0;             total = 0;             totalled = true;         }         static void setNumber(String Number)         {             numbersArray[numbersCounter] = Convert.ToInt16(Number);             storageVariable = null;             numbersCounter++;         }         static void setOperator(String Op)         {             operatorsArray[operatorsCounter] = Op;             operatorsCounter++;         }         private void AC_Click(object sender, RoutedEventArgs e)         {             Display.Content = "";             numbersArray = null;             operatorsArray = null;             storageVariable = null;             numbersCounter = 0;             operatorsCounter = 0;             total = 0;         }     } } 2  

Estoy usando este método de extensión que tomé prestado en desbordamiento de la pila (tuvo que modificarlo un poco), para hacer using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace NewCalculator { public partial class MainWindow : Window { static int[] numbersArray = new int[10]; static string[] operatorsArray = new string[9]; static string storageVariable; static int numbersCounter = 0; static int operatorsCounter = 0; static int total = 0; static bool totalled = false; public MainWindow() { InitializeComponent(); } private void One_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "1"; storageVariable += "1"; } private void Two_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "2"; storageVariable += "2"; } private void Three_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "3"; storageVariable += "3"; } private void Four_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "4"; storageVariable += "4"; } private void Five_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "5"; storageVariable += "5"; } private void Six_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "6"; storageVariable += "6"; } private void Seven_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "7"; storageVariable += "7"; } private void Eight_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "8"; storageVariable += "8"; } private void Nine_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "9"; storageVariable += "9"; } private void Zero_Click(object sender, RoutedEventArgs e) { if (totalled == true) { Display.Content = ""; totalled = false; } Display.Content += "0"; storageVariable += "0"; } private void Add_Click(object sender, RoutedEventArgs e) { setNumber(storageVariable); setOperator("+"); Display.Content += "+"; } private void Subtract_Click(object sender, RoutedEventArgs e) { setNumber(storageVariable); setOperator("-"); Display.Content += "-"; } private void Multiply_Click(object sender, RoutedEventArgs e) { setNumber(storageVariable); setOperator("*"); Display.Content += "x"; } private void Divide_Click(object sender, RoutedEventArgs e) { setNumber(storageVariable); setOperator("/"); Display.Content += "/"; } private void Equal_Click(object sender, RoutedEventArgs e) { setNumber(storageVariable); for (int i = 0; i < operatorsCounter; i++) { if (operatorsArray[i] == "+" && i == 0) { total = numbersArray[i] + numbersArray[i + 1]; } else if (operatorsArray[i] == "+") { total = total + numbersArray[i + 1]; } else if (operatorsArray[i] == "-" && i == 0) { total = numbersArray[i] - numbersArray[i + 1]; } else if (operatorsArray[i] == "-") { total = total - numbersArray[i + 1]; } else if (operatorsArray[i] == "*" && i == 0) { total = numbersArray[i] * numbersArray[i + 1]; } else if (operatorsArray[i] == "*") { total = total * numbersArray[i + 1]; } else if (operatorsArray[i] == "/" && i == 0) { total = numbersArray[i] / numbersArray[i + 1]; } else if (operatorsArray[i] == "/") { total = total / numbersArray[i + 1]; } } Display.Content = total; numbersArray = null; operatorsArray = null; storageVariable = null; numbersCounter = 0; operatorsCounter = 0; total = 0; totalled = true; } static void setNumber(String Number) { numbersArray[numbersCounter] = Convert.ToInt16(Number); storageVariable = null; numbersCounter++; } static void setOperator(String Op) { operatorsArray[operatorsCounter] = Op; operatorsCounter++; } private void AC_Click(object sender, RoutedEventArgs e) { Display.Content = ""; numbersArray = null; operatorsArray = null; storageVariable = null; numbersCounter = 0; operatorsCounter = 0; total = 0; } } } 3 Animaciones Es esperado y evite tener todas las animaciones que se ejecutan simultáneamente:

  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes;  namespace NewCalculator {     public partial class MainWindow : Window     {         static int[] numbersArray = new int[10];         static string[] operatorsArray = new string[9];          static string storageVariable;         static int numbersCounter = 0;         static int operatorsCounter = 0;         static int total = 0;         static bool totalled = false;          public MainWindow()         {             InitializeComponent();         }          private void One_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "1";             storageVariable += "1";         }         private void Two_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "2";             storageVariable += "2";         }         private void Three_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "3";             storageVariable += "3";         }         private void Four_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "4";             storageVariable += "4";         }         private void Five_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "5";             storageVariable += "5";         }         private void Six_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "6";             storageVariable += "6";         }         private void Seven_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "7";             storageVariable += "7";         }         private void Eight_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "8";             storageVariable += "8";         }         private void Nine_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "9";             storageVariable += "9";         }         private void Zero_Click(object sender, RoutedEventArgs e)         {             if (totalled == true)             {                 Display.Content = "";                 totalled = false;             }             Display.Content += "0";             storageVariable += "0";         }         private void Add_Click(object sender, RoutedEventArgs e)         {             setNumber(storageVariable);             setOperator("+");             Display.Content += "+";         }         private void Subtract_Click(object sender, RoutedEventArgs e)         {             setNumber(storageVariable);             setOperator("-");             Display.Content += "-";         }         private void Multiply_Click(object sender, RoutedEventArgs e)         {             setNumber(storageVariable);             setOperator("*");             Display.Content += "x";         }         private void Divide_Click(object sender, RoutedEventArgs e)         {             setNumber(storageVariable);             setOperator("/");             Display.Content += "/";         }         private void Equal_Click(object sender, RoutedEventArgs e)         {             setNumber(storageVariable);             for (int i = 0; i < operatorsCounter; i++)             {                 if (operatorsArray[i] == "+" && i == 0)                 {                     total = numbersArray[i] + numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "+")                 {                     total = total + numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "-" && i == 0)                 {                     total = numbersArray[i] - numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "-")                 {                     total = total - numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "*" && i == 0)                 {                     total = numbersArray[i] * numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "*")                 {                     total = total * numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "/" && i == 0)                 {                     total = numbersArray[i] / numbersArray[i + 1];                 }                 else if (operatorsArray[i] == "/")                 {                     total = total / numbersArray[i + 1];                 }             }             Display.Content = total;             numbersArray = null;             operatorsArray = null;             storageVariable = null;             numbersCounter = 0;             operatorsCounter = 0;             total = 0;             totalled = true;         }         static void setNumber(String Number)         {             numbersArray[numbersCounter] = Convert.ToInt16(Number);             storageVariable = null;             numbersCounter++;         }         static void setOperator(String Op)         {             operatorsArray[operatorsCounter] = Op;             operatorsCounter++;         }         private void AC_Click(object sender, RoutedEventArgs e)         {             Display.Content = "";             numbersArray = null;             operatorsArray = null;             storageVariable = null;             numbersCounter = 0;             operatorsCounter = 0;             total = 0;         }     } } 4  
Original en ingles

In Memoriam

Ralph H. Baer, co-inventor of the original "Simon" game, died Saturday December 6th 2014, at 92. With his passing, this friendly little challenge inadvertently became a memorial to the father of video game consoles. Rest in peace Mr. Baer, you have changed our lives forever.


I finally got my Simon Says implementation to work as I intended it to. That's great, but now I'm left with a mess and I'm not sure where to start cleaning up (full code on GitHub).

Per the specs, there was going to be 4 buttons. So I created an enum and called it SimonButton:

public enum SimonButton {     Green,     Red,     Blue,     Yellow } 

I created a SimonSaysRound class that implements INotifyPropertyChanged, to bind with the UI, mostly to provide the player's score.

public class SimonSaysRound : INotifyPropertyChanged {     private const int PointsForGoodMatch = 5;      private readonly SimonButton[] _sequence;     private int _matches;     private int _score;      public SimonSaysRound(IEnumerable<SimonButton> sequence, int score)     {         _sequence = sequence.ToArray();         _score = score;         _matches = 0;     }      public event EventHandler<SimonSaysScoreEventArgs> RoundCompleted;     public void OnRoundCompleted()     {         var handler = RoundCompleted;         if (handler != null)         {             var result = _matches == _sequence.Length;             RoundCompleted(this, new SimonSaysScoreEventArgs(result, Score));         }     }      public void Play(SimonButton button)     {         var success = _sequence[_matches] == button;         if (success)         {             Score += PointsForGoodMatch;             _matches++;         }          if (!success || _matches == _sequence.Length)         {             OnRoundCompleted();         }     }      public int Round     {         get { return _sequence.Length; }     }      public int Score     {         get { return _score; }         private set         {             if (value == _score) return;             _score = value;             OnPropertyChanged();         }     }      public int Length { get { return _sequence.Length; } }     public IEnumerable<SimonButton> Sequence { get { return _sequence; } }      public event PropertyChangedEventHandler PropertyChanged;      [NotifyPropertyChangedInvocator]     protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)     {         PropertyChangedEventHandler handler = PropertyChanged;         if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));     } } 

I don't normally implement my INotifyPropertyChanged like this - ReSharper suggested something, and I wanted to see what it did.. and I don't dislike it.

When the application starts, the main window is displayed, and an animation reveals a "Start" button:

Start!

When the button is clicked, the message bar collapses, and a button flashes by quickly animating a radial gradient's offset value (with accompanying sound effects):

Blue quadrant lit

When the player enters the correct sequence, the middle bar expands reveals a "round completed" message that shows the player their score; game resumes when the player clicks /collapses the message:

Round 1 completed! Ready?

The "Game Over" screen displays the player's score, and the number of completed rounds; clicking the message closes the window, and then the program ends:

Oops! 6 rounds completed. Your score: 115

The XAML/UI is reviewable here; this post is about the actual application code:

public partial class App : Application {     private readonly MainWindow _mainWindow = new MainWindow();     private SimonSaysRound _currentRound;      private readonly IDictionary<SimonButton, string> _sounds;      private readonly int _seed;      public App()     {         _seed = new Random().Next();          var folder = Path.GetDirectoryName(GetType().Assembly.Location);         _sounds = Enum.GetValues(typeof (SimonButton))                       .Cast<SimonButton>()                       .ToDictionary(button => button,                                     button => Path.Combine(folder ?? string.Empty, "Resources", button + ".wav"));     }      protected override void OnStartup(StartupEventArgs e)     {         _mainWindow.SimonButtonClicked += OnSimonButtonClick;         _mainWindow.PlayNextRound += _mainWindow_PlayNextRound;         _mainWindow.ShowDialog();     }      private void _mainWindow_PlayNextRound(object sender, EventArgs e)     {         PlayNextRound();     }      private void PlayNextRound()     {         var sequenceLength = 1;         var score = 0;         if (_currentRound != null)         {             sequenceLength = _currentRound.Length + 1;             score = _currentRound.Score;         }          _currentRound = new SimonSaysRound(GenerateSequence(sequenceLength), score);         _currentRound.RoundCompleted += _currentRound_RoundCompleted;         _mainWindow.DataContext = _currentRound;         _mainWindow.DataContext = _currentRound;         PlaySequence();     }      private IEnumerable<SimonButton> GenerateSequence(int length)     {         var random = new Random(_seed);         for (var i = 0; i < length; i++)         {             yield return (SimonButton)random.Next(Enum.GetValues(typeof(SimonButton)).GetLength(0));         }     }      private void _currentRound_RoundCompleted(object sender, SimonSaysRoundCompletedEventArgs e)     {         if (e.Success)         {             _mainWindow.OnRoundSuccessful();         }         else         {             _mainWindow.OnGameOver();         }     }      private async Task PlaySequence()     {         foreach (var button in _currentRound.Sequence)         {             await OnSimonButtonClickAsync(null, new SimonButtonEventArgs(button));             Thread.Sleep(300);         }     }      private void OnSimonButtonClick(object sender, SimonButtonEventArgs e)     {         OnSimonButtonClickAsync(sender, e);     }      private async Task OnSimonButtonClickAsync(object sender, SimonButtonEventArgs e)     {         using (var player = new SoundPlayer(_sounds[e.Button]))         {             player.Play();         }          if (sender != null)         {             _currentRound.Play(e.Button);         }          await _mainWindow.HighlightSimonButton(e.Button);     } } 

And the code-behind for the main window:

public partial class MainWindow : Window {     private readonly IDictionary<SimonButton, Border> _buttons;      public MainWindow()     {         InitializeComponent();         _buttons = new Dictionary<SimonButton, Border>             {                 { SimonButton.Green, Green },                 { SimonButton.Red, Red },                 { SimonButton.Yellow, Yellow },                 { SimonButton.Blue, Blue }             };          RegisterName(MessageBar.Name, MessageBar);         foreach (var button in _buttons)         {             RegisterName(button.Value.Name, button.Value);         }          DisableButtons();          MouseDown += MainWindow_MouseDown;         Activated += MainWindow_Activated;     }      private async void MainWindow_Activated(object sender, EventArgs e)     {         GameScoreLabel.Visibility = Visibility.Collapsed;         GameButton.Text = "Start!";          await AnimateMessageBand(36);         Activated -= MainWindow_Activated;          GameButton.MouseDown += GameButtonStartGame;     }      private void MainWindow_MouseDown(object sender, MouseButtonEventArgs e)     {         if (e.ChangedButton == MouseButton.Left)         {             DragMove();         }     }      public event EventHandler<SimonButtonEventArgs> SimonButtonClicked;     public async Task OnSimonButtonClicked(SimonButton button)     {         var handler = SimonButtonClicked;         if (handler != null)         {             handler.Invoke(this, new SimonButtonEventArgs(button));         }     }      public async Task OnGameOver()     {         GameButton.Text = string.Format("Oops! {0} rounds completed.", ((SimonSaysRound)DataContext).Round - 1);         GameScoreLabel.Visibility = Visibility.Visible;         await AnimateMessageBand(56);          DisableButtons();          GameButton.MouseDown += GameButtonEndGame;     }      private void DisableButtons()     {         Green.MouseDown -= Green_MouseDown;         Red.MouseDown -= Red_MouseDown;         Yellow.MouseDown -= Yellow_MouseDown;         Blue.MouseDown -= Blue_MouseDown;     }      public void EnableButtons()     {         Green.MouseDown += Green_MouseDown;         Red.MouseDown += Red_MouseDown;         Yellow.MouseDown += Yellow_MouseDown;         Blue.MouseDown += Blue_MouseDown;     }      public async Task OnRoundSuccessful()     {         DisableButtons();         GameButton.Text = string.Format("Round {0} completed! Ready?", ((SimonSaysRound)DataContext).Round);         GameScoreLabel.Visibility = Visibility.Visible;         await AnimateMessageBand(56);         GameButton.MouseDown += GameButtonNextRound;     }      private async Task AnimateMessageBand(double height)     {         var animation = new DoubleAnimation(height, new Duration(TimeSpan.FromMilliseconds(200)));          Storyboard.SetTargetName(animation, MessageBar.Name);         Storyboard.SetTargetProperty(animation, new PropertyPath("Height"));          var story = new Storyboard();         story.Children.Add(animation);         await story.BeginAsync(MessageBar);          story.Remove();     }      public async Task HighlightSimonButton(SimonButton button)     {         var border = _buttons[button];         var animation = new DoubleAnimation(0, 0.75, new Duration(TimeSpan.FromMilliseconds(100)));          Storyboard.SetTargetName(animation, button.ToString());         Storyboard.SetTargetProperty(animation, new PropertyPath("Background.GradientStops[1].Offset"));          var story = new Storyboard();         story.Children.Add(animation);         await story.BeginAsync(border);          story.Remove();     }      private void Blue_MouseDown(object sender, MouseButtonEventArgs e)     {         OnSimonButtonClicked(SimonButton.Blue);         e.Handled = true;     }      private void Yellow_MouseDown(object sender, MouseButtonEventArgs e)     {         OnSimonButtonClicked(SimonButton.Yellow);         e.Handled = true;     }      private void Green_MouseDown(object sender, MouseButtonEventArgs e)     {         OnSimonButtonClicked(SimonButton.Green);         e.Handled = true;     }      private void Red_MouseDown(object sender, MouseButtonEventArgs e)     {         OnSimonButtonClicked(SimonButton.Red);         e.Handled = true;     }      private async void GameButtonStartGame(object sender, MouseButtonEventArgs e)     {         await AnimateMessageBand(0);         e.Handled = true;          GameButton.MouseDown -= GameButtonStartGame;          var handler = PlayNextRound;         if (handler != null)         {             handler(this, EventArgs.Empty);         }         EnableButtons();     }      public event EventHandler PlayNextRound;     private async void GameButtonNextRound(object sender, MouseButtonEventArgs e)     {         await AnimateMessageBand(0);         e.Handled = true;          var handler = PlayNextRound;         if (handler != null)         {             handler(this, EventArgs.Empty);         }          GameButton.MouseDown -= GameButtonNextRound;         EnableButtons();     }      private void GameButtonEndGame(object sender, MouseButtonEventArgs e)     {         Close();         e.Handled = true;     } } 

I'm using this extension method I borrowed on Stack Overflow (had to tweak it a little), to make Storyboard animations awaitable and avoid having all animations running simultaneously:

public static class StoryboardExtensions {     public static Task BeginAsync(this Storyboard storyboard, FrameworkElement containingObject)     {         var source = new TaskCompletionSource<bool>();         if (storyboard == null)             source.SetException(new ArgumentNullException());         else         {             EventHandler onComplete = null;             onComplete = (sender, args) =>             {                 storyboard.Completed -= onComplete;                 source.SetResult(true);             };             storyboard.Completed += onComplete;             containingObject.Dispatcher.Invoke(() => storyboard.Begin(containingObject));         }         return source.Task;     } } 
              
   
   

Lista de respuestas

18
 
vote
vote
La mejor respuesta
 
  1. Bueno, las primeras preguntas son: ¿por qué no usas MVVM? Contenido de su clase App La clase parece algo que debe implementarse en el nivel de modelo de modelo / vista.
  2. Esto se parece a una gran cantidad de copia-pegado

      private void Blue_MouseDown(object sender, MouseButtonEventArgs e) {     OnSimonButtonClicked(SimonButton.Blue);     e.Handled = true; }  private void Yellow_MouseDown(object sender, MouseButtonEventArgs e) {     OnSimonButtonClicked(SimonButton.Yellow);     e.Handled = true; }  ....   

Debe usar el manejador de eventos único para sus botones. Por ejemplo, puede configurar el tipo de botón a FrameworkElement.Tag en XAML, y acceder a él como ((FrameworkElement)sender).Tag en el código detrás. También puede refactar a los que ingresan a los comandos, si desea usar enlaces en lugar de eventos.

  1. No me gusta su EnableButtons y 9988776655544335 , se sienten mal. Me endicaría IsEnabled propiedad de sus botones a una propiedad de dependencia de BOOL (o propiedad de ViewModel) y configúrela en True / Falso. Y luego revisaría esta propiedad en el manejador de eventos.

  2. Debe usar algún método estático para hacer esto:

      var handler = myEvent; if (handler != null) {     handler(this, myArgs); }   
  3. No sé toda la historia, pero no entiendo muy bien, ¿por qué necesitas esperar para las animaciones? Solo hace que su código sea más complejo. Además, creo que la gestión y la definición de los guiones gráficos es mucho más fácil en XAML que en el código, pero, podría ser una cuestión de gusto.

 
  1. Well, first questions is: why don't you use MVVM? Contents of your App class look like something that should be implemented on model/view model level.
  2. This looks like a lot of copy-pasting

    private void Blue_MouseDown(object sender, MouseButtonEventArgs e) {     OnSimonButtonClicked(SimonButton.Blue);     e.Handled = true; }  private void Yellow_MouseDown(object sender, MouseButtonEventArgs e) {     OnSimonButtonClicked(SimonButton.Yellow);     e.Handled = true; }  .... 

You should use single event handler for your buttons. For example, you can set button type to FrameworkElement.Tag in XAML, and access it as ((FrameworkElement)sender).Tag in code behind. You can also refactor those into commands, if you were to use bindings instead of events.

  1. I don't like your EnableButtons and DisableButtons methods, they feel wrong. I would bind IsEnabled property of your buttons to some bool dependency property (or viewmodel property), and set it to true/false instead. And I would then check this property in the event handler.

  2. You should use some static method to do this:

    var handler = myEvent; if (handler != null) {     handler(this, myArgs); } 
  3. I don't know the whole story, but I don't quite understand why do you need to await for animations. It only makes your code more complex. Also, I think that managing and defining storyboards is a lot easier in XAML than in code-behind, but, it might be a matter of taste.

 
 
15
 
vote
  • Magic números, tiene al menos uno de ellos en clase App : private async Task PlaySequence() Debe extraer esto a una propiedad constante o mejor para una propiedad, por lo que que la velocidad, alca de dormir menos, se puede ajustar.

  • No veo el punto del private void Blue_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Blue); e.Handled = true; } private void Yellow_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Yellow); e.Handled = true; } .... 0 variable. Sí, sé por qué lo usas, pero solo lo obliga, cada vez que se llama el método 99887766555443311 , para recrear el private void Blue_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Blue); e.Handled = true; } private void Yellow_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Yellow); e.Handled = true; } .... 2 . Considere agregar el elemento "nuevo" para la secuencia hasta el final de la secuencia.

  • Cada vez que llame a private void Blue_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Blue); e.Handled = true; } private void Yellow_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Yellow); e.Handled = true; } .... 3 en la creación del azar tampoco es necesario. Extraerlo a una variable y reutilizarlo, no cambiará ;-)
  • Asignación del private void Blue_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Blue); e.Handled = true; } private void Yellow_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Yellow); e.Handled = true; } .... 4 Dos veces podría ser una copia y un amplificador; Pegue el error
  • El método completo private void Blue_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Blue); e.Handled = true; } private void Yellow_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Yellow); e.Handled = true; } .... 5 debe vivir en la clase private void Blue_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Blue); e.Handled = true; } private void Yellow_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Yellow); e.Handled = true; } .... 6 . No necesitaría acceder a private void Blue_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Blue); e.Handled = true; } private void Yellow_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Yellow); e.Handled = true; } .... 7 y private void Blue_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Blue); e.Handled = true; } private void Yellow_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Yellow); e.Handled = true; } .... 8 Propiedades.
  • private void Blue_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Blue); e.Handled = true; } private void Yellow_MouseDown(object sender, MouseButtonEventArgs e) { OnSimonButtonClicked(SimonButton.Yellow); e.Handled = true; } .... 9 También podría deshacerse del FrameworkElement.Tag0 porque podría usar un 998877766655443321 en su lugar. Esto también resultará en FrameworkElement.Tag2 propiedad obteniendo obsoleto.

Refactoring El FrameworkElement.Tag3 Clase al implementar los puntos anteriores conducirá a

  FrameworkElement.Tag4  

y en el lado de llamada

  FrameworkElement.Tag5  

Debe considerar inicializar el FrameworkElement.Tag6 en el nivel de clase que hace que el nulo verifique obsoleto.

  • combinando el inicio de un juego y el inicio de la siguiente ronda al elevar el mismo evento sin distinguir entre ellos mediante el uso de diferentes argumentos de eventos, no es muy bueno.

  • Tiene un código duplicado en el FrameworkElement.Tag7 y 99887766555443328 Methods. Otorre uno de los métodos y cambie el evento, o extraiga mejor el código a un método separado que se llama formulario ambos manipuladores.

 
  • Magic numbers, you have at least one of them in class App: private async Task PlaySequence() you should extract this to either a constant or better to a property, so that the speed, aka less sleep, can be adjusted.

  • I don't see the point of the _seed variable. Yeah, I know why you use it, but it just forces you, each time the GenerateSequence() method is called, to recreate the IEnumerable<SimonButton>. Consider to append the "new" item for the sequence to the end of the sequence.

  • each time calling Enum.GetValues(typeof(SimonButton)).GetLength(0) at creating the random is not necessary either. Extract it to a variable and reuse it, it won't change ;-)
  • assigning the DataContext two times might be a copy & paste error
  • The whole GenerateSequence() method should live in the SimonSaysRound class. You wouldn't need to access Score and Length properties.
  • SimonSaysRound could also get rid of the SimonButton[] because it could use an IEnumerable<> instead. This will also result in Length property getting obsolete.

Refactoring the SimonSaysRound class by implementing the points above will lead to

public class SimonSaysRound : INotifyPropertyChanged {     private const int PointsForGoodMatch = 5;     private readonly int _buttonCount = Enum.GetValues(typeof(SimonButton)).GetLength(0);      private IEnumerable<SimonButton> _sequence = Enumerable.Empty<SimonButton>();     private IEnumerator<SimonButton> _enumerator;      private int _matches=0;     private int _score=0;     private int _currentlength = 0;      private Random _random = new Random();      /// <summary>     /// Use this method, to start a new game.     /// </summary>     public void Reset()     {         _matches = 0;         _score = 0;         _currentlength = 0;         _sequence = Enumerable.Empty<SimonButton>();     }      public event EventHandler<SimonSaysScoreEventArgs> RoundCompleted;     public void OnRoundCompleted()     {         var handler = RoundCompleted;         if (handler != null)         {             var result = _matches == _currentlength;             RoundCompleted(this, new SimonSaysScoreEventArgs(result, Score));         }     }      public void Play(SimonButton button)     {         _enumerator.MoveNext();         var success = _enumerator.Current == button;         if (success)         {             Score += PointsForGoodMatch;             _matches++;         }          if (!success || _matches == _currentlength)         {             OnRoundCompleted();         }     }      public int Round     {         get { return _currentlength; }     }      public int Score     {         get { return _score; }         private set         {             if (value == _score) return;             _score = value;             OnPropertyChanged();         }     }      public IEnumerable<SimonButton> Sequence { get { return _sequence; } }      public event PropertyChangedEventHandler PropertyChanged;      [NotifyPropertyChangedInvocator]     protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)     {         PropertyChangedEventHandler handler = PropertyChanged;         if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));     }      public void PlayNextRound()     {         _matches = 0;         _currentlength += 1;         _sequence = _sequence.Concat(GenerateNextSequenceItem());         _enumerator = _sequence.GetEnumerator();      }      private IEnumerable<SimonButton> GenerateNextSequenceItem()     {         yield return (SimonButton)_random.Next(_buttonCount);     }       } 

and on the calling side

private void PlayNextRound() {     if (_currentRound == null)     {         _currentRound = new SimonSaysRound();     }     _currentRound.PlayNextRound();     _currentRound.RoundCompleted += _currentRound_RoundCompleted;      _mainWindow.DataContext = _currentRound;      PlaySequence(); } 

You should consider to initialize the _currentRound on class level making the null check obsolete.

  • combining the start of a game and the start of the next round by raising the same event without to distinguish between them by using different event arguments, is IMHO not very good.

  • you have duplicate code in the GameButtonStartGame() and GameButtonNextRound() methods. Either remove one of the methods and change the eventhandler or better extract the code to a separate method which is called form both handlers.

 
 
6
 
vote

El nombramiento es inconsistente con el resto del código en el método de extensión prestado:

  FrameworkElement.Tag9  

((FrameworkElement)sender).Tag0 Y CADA UNO ((FrameworkElement)sender).Tag1 Ha escrito Llamadas The Handler ((FrameworkElement)sender).Tag2 :

  ((FrameworkElement)sender).Tag3  

Esto sería más consistente entonces, notificaría el ((FrameworkElement)sender).Tag44 la asignación es redundante y se ha eliminado:

  ((FrameworkElement)sender).Tag5  
 

The naming is inconsistent with the rest of the code in the borrowed extension method:

    EventHandler onComplete = null;     onComplete = (sender, args) =>     {         storyboard.Completed -= onComplete;         source.SetResult(true);     };     storyboard.Completed += onComplete;     containingObject.Dispatcher.Invoke(() => storyboard.Begin(containingObject)); 

OnSimonButtonClicked and every single OnEventName method you've ever written calls the handler handler:

    var handler = SimonButtonClicked;     if (handler != null)     {         handler.Invoke(this, new SimonButtonEventArgs(button));     } 

This would be more consistent then - notice the = null assignment is redundant and has been removed:

    EventHandler handler;     handler = (sender, args) =>     {         storyboard.Completed -= handler;         source.SetResult(true);     };     storyboard.Completed += handler;     containingObject.Dispatcher.Invoke(() => storyboard.Begin(containingObject)); 
 
 

Relacionados problema

5  Simon dice usando Arduino Uno  ( Simon says using arduino uno ) 
Construí un juego Simon, dice un juego de Arduino Uno. Este fue mi primer proyecto de Arduino "real". Me gustaría saber cómo mejorar, mecánica de juegos y efi...

5  Simon dice en unidad  ( Simon says in unity ) 
He hecho que el Simon dice juego en unidad Empieza por adivinar un patrón de 3 colores y cada vez que complete el patrón un nuevo, aleatorio, se genera y...

10  Simon-dice en AS3 - Funcionalidad de prototipos  ( Simon says in as3 prototyping functionality ) 
Mi entrada no grave para Simon dice. Basado en literal interpretación de las reglas: Crear una interfaz de usuario con cuatro botones de colores que se...

2  Creó un juego de Simon utilizando HTML, CSS y JavaScript  ( Created a game of simon using html css and javascript ) 
Aquí está el Fiddle JS: https://jsfiddle.net/4jo9hvpk/ El código es completamente funcional. ¿Podría alguien señalar algún error en estilo? ¿Cualquier red...

4  Simon en JavaScript  ( Simon in javascript ) 
Este es un juego de Simon usando Plain Javascript. Doy la bienvenida a cualquier comentario, sugerencias, Perspectivas o ideas para mejorar. Una opción que hi...

9  Animar y jugar sonidos en Simon dice 'el camino angular'  ( Animate and play sounds in simon says the angular way ) 
Soy un codificador de Newbie y estoy tratando de aprender buenos hábitos de codificación. Estoy haciendo un Simon, dice el juego desafío del campo de código g...

10  Juego Simon / Four Tiles Game  ( Simon game four tiles game ) 
Cuando leí la comunidad Challange, no podía esperar. Así que aquí voy con el primer juego de cuatro azulejos: pantas5 Editar: Si desea ver el juego con ...

12  Simon dice / Four Tiles Game, con C ++ y SDL  ( Simon says four tiles game with c and sdl ) 
Mi opinión en la PREBASH DESAFÍO ", dice Simon" Juego, en menos de 300 líneas de C ++ (más el archivo de encabezado), usando sdl para la gestión de la ven...

12  Simon dice en JavaScript (con Knockout) - Snippet de código jugable  ( Simon says in javascript with knockout playable code snippet ) 
Resolví hacer todo el asunto con JavaScript de Vanilla como un desafío, pero el hombre, la vinculación y la gestión estatal de Knockout es demasiado fácil. ...

2  Simon dice que la implementación usando jQuery  ( Simon says implementation using jquery ) 
Me encantaría recibir algunos comentarios sobre mi implementación de "Simon dice". No he seguido el original en el que he creado una nueva secuencia cada vez,...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos