Random number near the best guess (binary search with variety)

20%20AM

https://www.sharemygame.com/share/a5c3057c-f49b-4aed-97c6-58d2404c28cb

public class NumberWizard : MonoBehaviour
{
    [SerializeField] public int min = 1;
    [SerializeField] public int max = 1000;
    [SerializeField] public TextMeshProUGUI gameText;

    private int guess;
    private int numberOfGuesses;

    // Start is called before the first frame update
    void Start()
    {
        NewGuess();
        gameText.SetText("Is it " + guess + "?");
    }


    void NewGuess()
    {
        numberOfGuesses++;
        var bestGuess = Mathf.FloorToInt((min + max) / 2);
        var rangeMin = bestGuess - Mathf.FloorToInt((bestGuess - min) / 2);
        var rangeMax = bestGuess + Mathf.FloorToInt((max - bestGuess) / 2);
        guess = Random.Range(rangeMin, rangeMax);
    }

    public void OnPressHigher()
    {
        min = guess;
        NewGuess();
        gameText.SetText(guess + "?");
    }

    public void OnPressLower()
    {
        max = guess;
        NewGuess();
        gameText.SetText(guess + "?");
    }

}
2 Likes

Privacy & Terms