Another alternative to "max = max + 1" in Number Wizard

If the player presses Up or Down key, the correct number won’t be the value of the guess variable, so you can update the minimum = guess + 1 and maximum = guess - 1. This also avoids the “max = max + 1” bug.

using UnityEngine;

public class NumberWizard : MonoBehaviour
{
    int min = 1;
    int max = 1000;
    int guess = 500;

    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("Welcome to Number Wizard!");
        Debug.Log("Pick a number between " + min + " and " + max + ".");
        Debug.Log("Tell me if your number is higher or lower than " + guess + ".");
        Debug.Log("Keys: UP = higher, DOWN = lower, ENTER = correct.");
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.UpArrow))
        {
            min = guess + 1;
            guess = (min + max) / 2;
            Debug.Log("Is it higher or lower than " + guess + "?");
        }
        else if (Input.GetKeyDown(KeyCode.DownArrow))
        {
            max = guess - 1;
            guess = (min + max) / 2;
            Debug.Log("Is it higher or lower than " + guess + "?");
        }
        else if (Input.GetKeyDown(KeyCode.Return))
        {
            Debug.Log("I got it correct! The number is " + guess + "!");
        }
    }
}

2 Likes

Privacy & Terms