Checking win condition before looping Section 02 Lesson 43

For the last bit of code at the end of the SubmitValidGuess method it seems a bit strange to check the word length in order to set the win condition to true?

if (BullCowCount.Bulls == MyHiddenWord.length()) {
		bIsGameWon= true;
	}
else{
    BIsGameWon = false;
}

Yes, if you got all bulls then the word is correct, I get that. But why force the program to waste time looping if you already know the word is correct? Just do a direct comparison between the hidden word and the guess and you are done.

// receives a VALID guess, increments try, and returns count
FBullCowCount FBullCowGame::SubmitValidGuess(FString Guess)
{
	MyCurrentTry++;
	FBullCowCount BullCowCount;

	if (Guess == MyHiddenWord) {
		FBullCowGame::bGameIsWon = true;
		return BullCowCount;
	}

	// loop through all letters in the hidden word
	int32 WordLength = MyHiddenWord.length();
	for (int32 MyHWChar = 0; MyHWChar < WordLength; MyHWChar++)
	{
		// compare letters against the guess
		for (int32 GChar = 0; GChar < WordLength; GChar++)
		{
			if (MyHiddenWord[MyHWChar] == Guess[GChar])
			{
				if (MyHWChar == GChar)
				{
					// increment cows if they are not
					BullCowCount.Bulls++;
				}
				else
				{
					// increment bulls if they're in the same place
					BullCowCount.Cows++;
				}
			}

		}
	}
	return BullCowCount;
}

In the PlayGame I did this:

// Play the game
void PlayGame()
{
	BCGame.Reset();
	int32 MaxTries = BCGame.GetMaxTries();

	// loop asking for guesses while the game
	// is NOT won and there are still tries remaining
	while (!BCGame.isGameWon() && BCGame.GetCurrentTry() <= MaxTries)
	{
		FText Guess = GetValidGuess();

		// submit valid guess to the game, and receive counts
		FBullCowCount BullCowCount = BCGame.SubmitValidGuess(Guess);

		if (BCGame.isGameWon()) {
			std::cout << "You guessed correctly!  Good job!\n\n";
			break;  // we don't need the rest so break out of the loop here
		}

		std::cout << "Bulls = " << BullCowCount.Bulls;
		std::cout << ". Cows = " << BullCowCount.Cows << "\n\n";

	}
	// TODO add game summary
	
}

And thoughts?

Privacy & Terms