Some part of the presented code kept bugging me

Anyone correct me, if I am wrong, but in my opinion there is a “better” way it should be coded here:

The variable guess is being initialized with the value 500. When players say “higher” or “lower” the latest guess becomes either the new max or the new min.

My problem with this is, that our calculation then factors in a number we already know is invalid. If we start of with 500 and players say their number is higher, than in my opinion the new min should be guess + 1 (501) and not just guess (500). Why factor 500 in again? We already guessed it. The same goes for the other direction where a player says “lower” and the new max should be guess - 1 (499) instead of just guess (500) again.

This makes logically more sense to me and also prevented me from having to declare max = max + 1 in order to do any kind of bug fixing because 1.000 and 1 couldn’t be reached properly. Basically my code looks like this for this particular lesson:

public class NumberWizard : MonoBehaviour
{
    int maxGuess = 1000;
    int minGuess = 1;
    int guess = 500;

    // Start is called before the first frame update
    void Start()
    {       
        Debug.Log("Welcome to Number Wizard, Yo!");
        Debug.Log("Pick a number, keep it to yourself");
        Debug.Log("The highest number to pick is: " + maxGuess);
        Debug.Log("The lowest number to pick is: " + minGuess);
        Debug.Log("Tell me if your number is higher or lower than: " + guess);
        Debug.Log("Push Arrow Up = Higher, Push Arrow Down = Lower, Push Enter = Correct");
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            minGuess = guess + 1;
            guess = (maxGuess + minGuess) / 2;
            Debug.Log("Is your number: " + guess);
        }

        else if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            maxGuess = guess - 1;
            guess = (maxGuess + minGuess) / 2;
            Debug.Log("Is your number: " + guess);
        }

        else if (Input.GetKeyDown(KeyCode.Return))
        {
            Debug.Log("HA! I got it!");
        }
    }
}

Privacy & Terms