Avoiding Same Guesses

Hello everybody,

I made couple of changes to our code. If anyone would like to check here it is. Basically what it does is it doesnt guess the same number again and if max and min values are equal it prevents the guess value so we cant go any lower or higher. Here is my code:

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class NumberWizards : MonoBehaviour
{
int max, min, guess;
int maxGuessesAllowed;

private Text text;

// This function to get text object before game starts
private void Awake()
{
    // To get text component by code instead of from inspector
    text = GameObject.Find("Guess").GetComponent<Text>();
}

void Start()
{
    StartGame();
}

void StartGame()
{
    // I defined my variables here so if we return here by any chance instead of calling the scene from start
    // these variables will always be resetted to the numbers we write here.  If we defined them at the top it wouldnt reset. 
    max = 1000;
    min = 1;
    maxGuessesAllowed = 30;       

    NextGuess();
}

public void NextGuess()
{
    // Checking if the computer has any chance left to guess. If not opens Win Scene which means a win for user.
    // Not >= Because by doing like this actually it counts the first guess too. Because we actually don't decrease the value at the start
    if (maxGuessesAllowed > 0)
    {
        Guess();
    }
    else
    {
        SceneManager.LoadScene("Win");
    }
}

public void Guess()
{
    // Here i added +1 to make the max value inclusive from exclusive
    guess = Random.Range(min, max + 1);
    text.text = guess.ToString();
    maxGuessesAllowed--;
}

public void GuessLower()
{
    // This if condition prevents our variables values from user in case of clicking buttons if max and mins numbers are equalized.
    if (max > min)
    {
        // Here I added -1 to prevent computer to make same guess. 
        // This -1 first then it increases in random.Range as +1 and since its exclusive we make it automatically unguessable.
        max = guess - 1;
        NextGuess();
    }
}

public void GuessHigher()
{
    // This if condition prevents our variables values from user in case of clicking buttons if max and mins numbers are equalized.
    if (max > min)
    {
        // Here +1 prevents guess to be the last guess. If we didnt add this, since min is inclusive we wouldnt be able to stop computer to guess the last min again.
        min = guess + 1;
        NextGuess();
    }
}

}

A question why some of code in the text editor itself and why some of them are in C# typed window above? How can i make them stay all in that automatically created window?
Cheers.

2 Likes

I also noticed the oversight by the instructor here. Had some issues working out how to remedy it. Thanks. This helped!

I think there’s still a chance for a bug in your GuessHigher() and GuessLower() functions.

If the max is 1000 and the next guess is 1000 and the user presses higher, the new min is 1001. This causes the Random.Range function to return 1001 as min = 1001 and max = 1000. (Bug in Random.Range?) I’m using Unity 5.6.3.

My fix is as follows:

public void GuessHigher()
{
    // This if condition prevents our variables values from user in case of clicking buttons if max and mins numbers are equalized.
    if (max > guess)
    {
         .....
    }
}

public void GuessLower()
{
    // This if condition prevents our variables values from user in case of clicking buttons if max and mins numbers are equalized.
    if (guess > min)
    {
        ....
    }
}

Hope that helps. It worked for me.

I also added another scene that pops up if the user tries to cheat and there are no more moves left in the direction the user clicks.:wink:

PaulD

1 Like

FURTHER EDIT

I’ve fixed it! Turns out I just needed to correctly add the else if’s to the Higher/Lower functions. Below is the code if you’d like to see.

https://pastebin.com/bjzts0zy

Edit

On further tests, this happens regardless when the last logical number is guessed.

E.g. User thinks of 444, when 445 and 443 have been ruled out, computer assumes player is cheating…


Hey!

I tried this as I couldn’t move on without resolving the duplicated guesses issue and I also wanted to make sure that the user couldn’t cheat.

It seems to have resolved the issue, however it is now conflicting with my “cheat” code.

Observed Behaviour

If user selected number is 1,000 or 1, page auto directs to the “cheat/liar” page on selection of the “Higher” or “Lower” buttons respectively.

Expected Behaviour

Game will propose 1,000 or 1 as a guess before deciding if user is lying/cheating and wait for a button press to continue.

Steps to Reproduce

Added an “else if” to the NextGuess method, which loads a new level/scene when the min is identified as equal to the max.

https://pastebin.com/xVCjQDm3

What I’ve tried

I’ve attempted to add the else if to the GuessHigher/Lower methods individually, however this has not worked.

I believe there must be another way to determine if the user is cheating as I imagine that the min == max is being identified due to the max > guess or vice versa.

Thanks!

@bassman00 This is perfect. I was starting to develop some convoluted solution to this issue but your answer so elegantly and simply solved it for me. I hope I can come up with logic like that on my own one day!

Actually, I’ve come across another (hopefully final) glitch in my code: The player can endlessly click between Higher and Lower until the computer runs out of guesses. You can try my current build out here:

Number Wizard UI v.02

Below is my NumberWizard.cs code. If anyone has any ideas on how to prevent the player being able to do this, help would be much appreciated. I tried to implement logic in MakeGuess() but have a feeling I’d need to make use of a variable storing the old guess value in order to compare with the new guess value… If there’s a more elegant way, I’d love to know about it though!

using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class NumberWizard : MonoBehaviour
{
    int max;
    int min;
    int newGuess;
    public int guess;
    public int maxGuessesAllowed = 10;

    public Text text;
    public Text guessesRemaining;

    // Use this for initialization
    void Start()
    {
        StartGame();
    }

    void StartGame()
    {
        max = 1000;
        min = 1;

        MakeGuess();
        UpdateDisplay();
    }

    public void GuessHigher()
    {
        if (max > guess)
        {
            min = guess;
            NextGuess();
        }
        else if (max <= guess) { SceneManager.LoadScene("Lose2"); }
    }

    public void GuessLower()
    {
        if (min < guess)
        {
            max = guess;
            NextGuess();
        }
        else if (min >= guess) { SceneManager.LoadScene("Lose2"); }
    }

    public void GuessCorrect()
    {
        StartGame();
        SceneManager.LoadScene("Lose");
    }

    void NextGuess()
    {
        if (maxGuessesAllowed <= 0) SceneManager.LoadScene("Win");

        MakeGuess();
        maxGuessesAllowed -= 1;
        UpdateDisplay();
    }

    void UpdateDisplay()
    {
        text.text = guess.ToString() + " ?";
        guessesRemaining.text = maxGuessesAllowed.ToString();
    }

    void MakeGuess()
    {
        //guess = (max + min) / 2; // old guessing method

        bool validGuess = false;

        newGuess = GenerateNumber();

        while (validGuess == false)
        {
            // check if number has been guessed before
            if (newGuess == guess)
            {
                newGuess = GenerateNumber();
                Debug.Log("Number has been guessed before.");
            }
            else
            {
                validGuess = true;
                guess = newGuess;
                Debug.Log("Valid guess.");
            }

            Debug.Log("Min: " + min);
            Debug.Log("Max: " + max);
            Debug.Log("====================");
        }
    }

    int GenerateNumber() {
        int result = Random.Range(min, max + 1); return result;
    }
}

I saw another post earlier where someone used an Equality Operator to make a comparative between guess and previous guess (in this case its a != operator); if the guess and previous guess are equal the guess count does not subtract one from the guess count. Soooo, something like this:

if (guess != previousGuess) {drop the guess count by 1}

You’ll have to add a private int for previousGuess, and then after the guess is made, assign it to previousGuess. I hope I’m making sense- I think you can figure out how to do it (if I understand your question correctly).

Sippin Coffee,

E~

Privacy & Terms