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.