Solution for the challenge

This is how I managed to solve it, not sure if best practice for C++.

// Fill out your copyright notice in the Description page of Project Settings.
#include "BullCowCartridge.h"

void UBullCowCartridge::BeginPlay() // When the game starts
{
    Super::BeginPlay();
    SetupGame();
}

void UBullCowCartridge::OnInput(const FString& Input) // When the player hits enter
{
  ClearScreen();

  if (bGameOver)
  {
    SetupGame();
    return;
  }

  if (Input == HiddenWord)
  {
    EndGame(true);
  }
  else
  {
    --Lives;
    
    if (Input.Len() != HiddenWord.Len())
    {
      PrintLine(TEXT("The hidden word has %i characters!"), HiddenWord.Len());
      PrintLine(TEXT("Your guess had %i."), Input.Len());
      CheckLives();      
    }
    else
    {
      PrintLine(TEXT("Wrong answer!"));
      CheckLives();
    }
  }
  
}

void UBullCowCartridge::SetupGame()
{
  HiddenWord = TEXT("melon");
  Lives = HiddenWord.Len();
  bGameOver = false;

  PrintLine(TEXT("Welcome to Bulls and Cows game!"));
  PrintLine(TEXT("Try and guess the %i letter isogram"), HiddenWord.Len());
  PrintLine(TEXT("You got %i lives"), Lives);
}

void UBullCowCartridge::EndGame(bool bIsWon)
{
  bGameOver = true;
  switch (bIsWon)
  {
  case true:
    PrintLine(TEXT("Congratulations, you have won the game!"));
    PrintLine(TEXT("hit Enter to start a new one..."));
    break;
  case false:
    PrintLine(TEXT("You ran out of lives."));
    PrintLine(TEXT("hit Enter to start a new game..."));
    break;
  }
}

void UBullCowCartridge::CheckLives()
{
  if (Lives <= 0)
  {
    EndGame(false);
  }
  else
  {
    PrintLine(TEXT("You got %i lives left..."), Lives);
    PrintLine(TEXT("Try another guess"));
  }
}
1 Like

Everything looks pretty good!

1 Like

Thank you!

Privacy & Terms