Hi All,
Created a little code here which includes the following features:
- Player can keep pressing higher and lower and still get either 1 or 1000.
- If player decides that they want to go back, the code will record 3 repeats so it finds a new random guess between the guess and either the max or min depending on what the player chose.
- I found a little bug where if I pressed ‘higher’ and ‘lower’ randomly, sometimes it may do the opposite, so I did a check for if the old guess was greater than the new guess and I had press lower, I retried the 'OnPressHigher()" function until it became higher than guess.
Hope you find some ideas and if you have some feedback, please let me know. I understand it’s a bit messy so that could be something to keep in mind.
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System.Collections.Generic;
public class NumberWizardScript : MonoBehaviour
{
[SerializeField] int mini;
[SerializeField] int maxi;
[SerializeField] TextMeshProUGUI guessText;
List<int> guesses = new List<int>();
int guess;
int repeat;
bool newGuess = true;
bool higher = false;
bool lower = false;
void Start()
{
NextGuess();
}
public void OnPressHigher()
{
mini = Random.Range(guess, maxi);
higher = true;
NextGuess();
}
public void OnPressLower()
{
maxi = Random.Range(mini, guess);
lower = true;
NextGuess();
}
private void NextGuess()
{
if (newGuess == true)
{
repeat = 0;
newGuess = false;
if (higher == true)
{
mini = guess;
maxi = 1001;
guess = Random.Range(guess, maxi);
}
else if (lower == true)
{
mini = 1;
maxi = guess;
guess = Random.Range(mini, guess);
}
else
{
guess = Random.Range(1, 1001);
}
guesses.Add(guess);
}
else
{
int oldguess = guess;
guess = (mini + maxi) / 2;
if (higher == true)
{
if (oldguess > guess)
{
OnPressHigher();
}
}
if (lower == true)
{
if (oldguess < guess)
{
OnPressLower();
}
}
CheckIfSame();
}
guessText.text = guess.ToString();
lower = false;
higher = false;
}
private void CheckIfSame()
{
for (int i = 0; i < guesses.Count; i++)
{
if (guess == guesses[i])
{
repeat++;
if (repeat >= 3) {
guesses.Clear();
newGuess = true;
guessText.text = guess.ToString();
NextGuess();
}
}
}
guesses.Add(guess);
}
}