private async Task ValidateLetter() { Attempts++; var wordArray = Word.ToCharArray(); if (wordArray.Contains(Letter)) { foreach (Match m in Regex.Matches(Word, Letter.ToString())) { Letters[m.Index] = Letter; } if (!Letters.Any(c => c == '_')) { await Win(); } } else { IncorrectLetters.Add(Letter); SetImage(); if (IncorrectLetters.Count == 6) { await Loose(); } } }
private void FetchGameState() { _lastGameState = new HangmanGameState() { CorrectAttempts = CorrectLetters.Count, FailedAttempts = IncorrectLetters.Count, CorrectLetters = CorrectLetters.Select(str => (String)str.Clone()).ToList(), IncorrectLetters = IncorrectLetters.Select(str => (String)str.Clone()).ToList(), Difficulty = Difficulty, FoundLetters = DisplayWord.Replace(" ", String.Empty).Count(f => f != '_'), TotalLetters = GivenWord.Length, State = _lastState, TimeElapsed = _stopwatch.Elapsed, DisplayWord = DisplayWord }; }
public void TryLetter(String letter) { if (String.IsNullOrEmpty(letter)) { throw new HangmanException("TryLetter(string) expected a Letter of the English Alphabet. Got empty or null string"); } if (letter.Length > 1) { throw new HangmanException("TryLetter(string) expected a Letter of the English Alphabet. Got " + letter); } if (letter.Any(x => !char.IsLetter(x))) { throw new HangmanException("TryLetter(string) expected a Letter of the English Alphabet. Got " + letter); } if (!IsGameStarted) { throw new HangmanGameNotStartedException(); } _lastState = HangmanState.LetterTried; var c = letter.ToUpper(); if (GivenWord.Contains(c)) { if (!CorrectLetters.Contains(c)) { CorrectLetters.Add(c); FetchGameState(); OnAttempt?.Invoke(_lastGameState); } } else { if (!IncorrectLetters.Contains(c)) { IncorrectLetters.Add(c); FetchGameState(); OnAttempt?.Invoke(_lastGameState); } } CheckGameState(); }
public void StartGame(String word = null) { if (IsGameStarted) { throw new HangmanGameAlreadyStartedException(); } if (_difficultyPending != null) { _difficulty = _difficultyPending; _difficultyPending = null; } var client = new WebClient(); if (word != null) { GivenWord = word.ToUpper(); } else { var wordLength = _random.Next(_difficulty.MinimumLetters, 20); try { var data = client.DownloadString(WordProvider).ToUpper(); var strings = JsonConvert.DeserializeObject <String[]>(data); GivenWord = strings[0]; } catch (WebException) { throw new HangmanGameUnableToStartException("Couldn't fetch a random word from Online API"); } } _lastState = HangmanState.Started; CorrectLetters.Clear(); IncorrectLetters.Clear(); _timer.Start(); _stopwatch.Reset(); _stopwatch.Start(); IsGameStarted = true; FetchGameState(); OnStart?.Invoke(_lastGameState); }